Fix content language message cache (table of contents test depends on this)
[mediawiki.git] / includes / GlobalFunctions.php
blob3da1c53210f6d80926294bf00ca6b4ca9d22a8fa
1 <?php
2 # $Id$
4 /**
5 * Global functions used everywhere
6 * @package MediaWiki
7 */
9 /**
10 * Some globals and requires needed
13 /**
14 * Total number of articles
15 * @global integer $wgNumberOfArticles
17 $wgNumberOfArticles = -1; # Unset
18 /**
19 * Total number of views
20 * @global integer $wgTotalViews
22 $wgTotalViews = -1;
23 /**
24 * Total number of edits
25 * @global integer $wgTotalEdits
27 $wgTotalEdits = -1;
30 require_once( 'DatabaseFunctions.php' );
31 require_once( 'UpdateClasses.php' );
32 require_once( 'LogPage.php' );
33 require_once( 'normal/UtfNormalUtil.php' );
35 /**
36 * Compatibility functions
37 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
38 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
39 * such as the new autoglobals.
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 if( !function_exists('file_get_contents') ) {
54 # Exists in PHP 4.3.0+
55 function file_get_contents( $filename ) {
56 return implode( '', file( $filename ) );
60 if( !function_exists('is_a') ) {
61 # Exists in PHP 4.2.0+
62 function is_a( $object, $class_name ) {
63 return
64 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
65 is_subclass_of( $object, $class_name );
69 # UTF-8 substr function based on a PHP manual comment
70 if ( !function_exists( 'mb_substr' ) ) {
71 function mb_substr( $str, $start ) {
72 preg_match_all( '/./us', $str, $ar );
74 if( func_num_args() >= 3 ) {
75 $end = func_get_arg( 2 );
76 return join( '', array_slice( $ar[0], $start, $end ) );
77 } else {
78 return join( '', array_slice( $ar[0], $start ) );
83 /**
84 * html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
85 * with no UTF-8 support.
87 * @param string $string String having html entities
88 * @param $quote_style
89 * @param string $charset Encoding set to use (default 'ISO-8859-1')
91 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT, $charset='ISO-8859-1' ) {
92 static $trans;
93 static $savedCharset;
94 if( !isset( $trans ) || $savedCharset != $charset ) {
95 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
96 $savedCharset = $charset;
97 # Assumes $charset will always be the same through a run, and only understands
98 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
99 # ones will result in a bad link.
100 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
101 $trans = array_map( 'utf8_encode', $trans );
104 return strtr( $string, $trans );
109 * Where as we got a random seed
110 * @var bool $wgTotalViews
112 $wgRandomSeeded = false;
115 * Seed Mersenne Twister
116 * Only necessary in PHP < 4.2.0
118 * @return bool
120 function wfSeedRandom() {
121 global $wgRandomSeeded;
123 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
124 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
125 mt_srand( $seed );
126 $wgRandomSeeded = true;
131 * Get a random decimal value between 0 and 1, in a way
132 * not likely to give duplicate values for any realistic
133 * number of articles.
135 * @return string
137 function wfRandom() {
138 # The maximum random value is "only" 2^31-1, so get two random
139 # values to reduce the chance of dupes
140 $max = mt_getrandmax();
141 $rand = number_format( mt_rand() * mt_rand()
142 / $max / $max, 12, '.', '' );
143 return $rand;
147 * We want / and : to be included as literal characters in our title URLs.
148 * %2F in the page titles seems to fatally break for some reason.
150 * @param string $s
151 * @return string
153 function wfUrlencode ( $s ) {
154 $s = urlencode( $s );
155 $s = preg_replace( '/%3[Aa]/', ':', $s );
156 $s = preg_replace( '/%2[Ff]/', '/', $s );
158 return $s;
162 * Return the UTF-8 sequence for a given Unicode code point.
163 * Currently doesn't work for values outside the Basic Multilingual Plane.
165 * @param string $codepoint UTF-8 code point.
166 * @return string HTML UTF-8 Entitie such as '&#1234;'.
168 function wfUtf8Sequence( $codepoint ) {
169 if($codepoint < 0x80) return chr($codepoint);
170 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
171 chr($codepoint & 0x3f | 0x80);
172 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
173 chr($codepoint >> 6 & 0x3f | 0x80) .
174 chr($codepoint & 0x3f | 0x80);
175 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 | 0xf0) .
176 chr($codepoint >> 12 & 0x3f | 0x80) .
177 chr($codepoint >> 6 & 0x3f | 0x80) .
178 chr($codepoint & 0x3f | 0x80);
180 # There should be no assigned code points outside this range, but...
181 return "&#$codepoint;";
185 * Converts numeric character entities to UTF-8
187 * @param string $string String to convert.
188 * @return string Converted string.
190 function wfMungeToUtf8( $string ) {
191 global $wgInputEncoding; # This is debatable
192 #$string = iconv($wgInputEncoding, "UTF-8", $string);
193 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
194 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
195 # Should also do named entities here
196 return $string;
200 * Converts a single UTF-8 character into the corresponding HTML character
201 * entity (for use with preg_replace_callback)
203 * @param array $matches
206 function wfUtf8Entity( $matches ) {
207 $codepoint = utf8ToCodepoint( $matches[0] );
208 return "&#$codepoint;";
212 * Converts all multi-byte characters in a UTF-8 string into the appropriate
213 * character entity
215 function wfUtf8ToHTML($string) {
216 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
220 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
221 * In normal operation this is a NOP.
223 * Controlling globals:
224 * $wgDebugLogFile - points to the log file
225 * $wgProfileOnly - if set, normal debug messages will not be recorded.
226 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
227 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
229 * @param string $text
230 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
232 function wfDebug( $text, $logonly = false ) {
233 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
235 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
236 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
237 return;
240 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
241 $wgOut->debug( $text );
243 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
244 error_log( $text, 3, $wgDebugLogFile );
249 * Log for database errors
250 * @param string $text Database error message.
252 function wfLogDBError( $text ) {
253 global $wgDBerrorLog;
254 if ( $wgDBerrorLog ) {
255 $text = date('D M j G:i:s T Y') . "\t".$text;
256 error_log( $text, 3, $wgDBerrorLog );
261 * @todo document
263 function logProfilingData() {
264 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
265 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
266 $now = wfTime();
268 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
269 $start = (float)$sec + (float)$usec;
270 $elapsed = $now - $start;
271 if ( $wgProfiling ) {
272 $prof = wfGetProfilingOutput( $start, $elapsed );
273 $forward = '';
274 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
275 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
276 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
277 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
278 if( !empty( $_SERVER['HTTP_FROM'] ) )
279 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
280 if( $forward )
281 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
282 if($wgUser->getId() == 0)
283 $forward .= ' anon';
284 $log = sprintf( "%s\t%04.3f\t%s\n",
285 gmdate( 'YmdHis' ), $elapsed,
286 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
287 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
288 error_log( $log . $prof, 3, $wgDebugLogFile );
294 * Check if the wiki read-only lock file is present. This can be used to lock
295 * off editing functions, but doesn't guarantee that the database will not be
296 * modified.
297 * @return bool
299 function wfReadOnly() {
300 global $wgReadOnlyFile;
302 if ( '' == $wgReadOnlyFile ) {
303 return false;
305 return is_file( $wgReadOnlyFile );
310 * Get a message from anywhere, for the UI elements
312 function wfMsg( $key ) {
313 global $wgRequest;
315 if ( $wgRequest->getVal( 'debugmsg' ) ) {
316 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
317 return "/^()(.*)$/sD";
318 else
319 return $key;
321 $args = func_get_args();
322 if ( count( $args ) ) {
323 array_shift( $args );
325 return wfMsgReal( $key, $args, true );
329 * Get a message from anywhere, for the content
331 function wfMsgForContent( $key ) {
332 global $wgRequest;
333 if ( $wgRequest->getVal( 'debugmsg' ) ) {
334 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
335 return "/^()(.*)$/sD";
336 else
337 return $key;
339 $args = func_get_args();
340 if ( count( $args ) ) {
341 array_shift( $args );
343 return wfMsgReal( $key, $args, true, true );
349 * Get a message from the language file, for the UI elements
351 function wfMsgNoDB( $key ) {
352 $args = func_get_args();
353 if ( count( $args ) ) {
354 array_shift( $args );
356 return wfMsgReal( $key, $args, false );
360 * Get a message from the language file, for the content
362 function wfMsgNoDBForContent( $key ) {
364 $args = func_get_args();
365 if ( count( $args ) ) {
366 array_shift( $args );
368 return wfMsgReal( $key, $args, false, true );
373 * Really get a message
375 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
376 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
377 global $wgParser, $wgMsgParserOptions;
378 global $wgContLang, $wgLanguageCode;
380 $fname = 'wfMsg';
381 wfProfileIn( $fname );
383 if($forContent) {
384 global $wgMessageCache;
385 $cache = &$wgMessageCache;
386 $lang = &$wgContLang;
388 else {
389 if(in_array($wgLanguageCode, $wgContLang->getVariants())){
390 global $wgLang, $wgMessageCache;
391 $cache = &$wgMessageCache;
392 $lang = $wgLang;
394 else {
395 global $wgLang;
396 $cache = false;
397 $lang = &$wgLang;
402 if ( is_object($cache) ) {
403 $message = $cache->get( $key, $useDB, $forContent );
404 } elseif (is_object($lang)) {
405 wfSuppressWarnings();
406 $message = $lang->getMessage( $key );
407 wfRestoreWarnings();
408 if(!$message)
409 $message = Language::getMessage($key);
410 if(strstr($message, '{{' ) !== false) {
411 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
413 } else {
414 wfDebug( "No language object when getting $key\n" );
415 $message = "&lt;$key&gt;";
418 # Replace arguments
419 if( count( $args ) ) {
420 $message = str_replace( $replacementKeys, $args, $message );
422 wfProfileOut( $fname );
423 return $message;
429 * Just like exit() but makes a note of it.
430 * Commits open transactions except if the error parameter is set
432 function wfAbruptExit( $error = false ){
433 global $wgLoadBalancer;
434 static $called = false;
435 if ( $called ){
436 exit();
438 $called = true;
440 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
441 $bt = debug_backtrace();
442 for($i = 0; $i < count($bt) ; $i++){
443 $file = $bt[$i]['file'];
444 $line = $bt[$i]['line'];
445 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
447 } else {
448 wfDebug('WARNING: Abrupt exit\n');
450 if ( !$error ) {
451 $wgLoadBalancer->closeAll();
453 exit();
457 * @todo document
459 function wfErrorExit() {
460 wfAbruptExit( true );
464 * Die with a backtrace
465 * This is meant as a debugging aid to track down where bad data comes from.
466 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
468 * @param string $msg Message shown when dieing.
470 function wfDebugDieBacktrace( $msg = '' ) {
471 global $wgCommandLineMode;
473 if ( function_exists( 'debug_backtrace' ) ) {
474 if ( $wgCommandLineMode ) {
475 $msg .= "\nBacktrace:\n";
476 } else {
477 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
479 $backtrace = debug_backtrace();
480 foreach( $backtrace as $call ) {
481 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
482 $file = $f[count($f)-1];
483 if ( $wgCommandLineMode ) {
484 $msg .= "$file line {$call['line']} calls ";
485 } else {
486 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
488 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
489 $msg .= $call['function'] . '()';
491 if ( $wgCommandLineMode ) {
492 $msg .= "\n";
493 } else {
494 $msg .= "</li>\n";
498 die( $msg );
502 /* Some generic result counters, pulled out of SearchEngine */
506 * @todo document
508 function wfShowingResults( $offset, $limit ) {
509 global $wgLang;
510 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
514 * @todo document
516 function wfShowingResultsNum( $offset, $limit, $num ) {
517 global $wgLang;
518 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
522 * @todo document
524 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
525 global $wgUser, $wgLang;
526 $fmtLimit = $wgLang->formatNum( $limit );
527 $prev = wfMsg( 'prevn', $fmtLimit );
528 $next = wfMsg( 'nextn', $fmtLimit );
530 if( is_object( $link ) ) {
531 $title =& $link;
532 } else {
533 $title =& Title::newFromText( $link );
534 if( is_null( $title ) ) {
535 return false;
539 $sk = $wgUser->getSkin();
540 if ( 0 != $offset ) {
541 $po = $offset - $limit;
542 if ( $po < 0 ) { $po = 0; }
543 $q = "limit={$limit}&offset={$po}";
544 if ( '' != $query ) { $q .= '&'.$query; }
545 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
546 } else { $plink = $prev; }
548 $no = $offset + $limit;
549 $q = 'limit='.$limit.'&offset='.$no;
550 if ( '' != $query ) { $q .= '&'.$query; }
552 if ( $atend ) {
553 $nlink = $next;
554 } else {
555 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
557 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
558 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
559 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
560 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
561 wfNumLink( $offset, 500, $title, $query );
563 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
567 * @todo document
569 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
570 global $wgUser, $wgLang;
571 if ( '' == $query ) { $q = ''; }
572 else { $q = $query.'&'; }
573 $q .= 'limit='.$limit.'&offset='.$offset;
575 $fmtLimit = $wgLang->formatNum( $limit );
576 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
577 return $s;
581 * @todo document
582 * @todo FIXME: we may want to blacklist some broken browsers
584 * @return bool Whereas client accept gzip compression
586 function wfClientAcceptsGzip() {
587 global $wgUseGzip;
588 if( $wgUseGzip ) {
589 # FIXME: we may want to blacklist some broken browsers
590 if( preg_match(
591 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
592 $_SERVER['HTTP_ACCEPT_ENCODING'],
593 $m ) ) {
594 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
595 wfDebug( " accepts gzip\n" );
596 return true;
599 return false;
603 * Yay, more global functions!
605 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
606 global $wgRequest;
607 return $wgRequest->getLimitOffset( $deflimit, $optionname );
611 * Escapes the given text so that it may be output using addWikiText()
612 * without any linking, formatting, etc. making its way through. This
613 * is achieved by substituting certain characters with HTML entities.
614 * As required by the callers, <nowiki> is not used. It currently does
615 * not filter out characters which have special meaning only at the
616 * start of a line, such as "*".
618 * @param string $text Text to be escaped
620 function wfEscapeWikiText( $text ) {
621 $text = str_replace(
622 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
623 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
624 htmlspecialchars($text) );
625 return $text;
629 * @todo document
631 function wfQuotedPrintable( $string, $charset = '' ) {
632 # Probably incomplete; see RFC 2045
633 if( empty( $charset ) ) {
634 global $wgInputEncoding;
635 $charset = $wgInputEncoding;
637 $charset = strtoupper( $charset );
638 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
640 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
641 $replace = $illegal . '\t ?_';
642 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
643 $out = "=?$charset?Q?";
644 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
645 $out .= '?=';
646 return $out;
650 * @todo document
651 * @return float
653 function wfTime() {
654 $st = explode( ' ', microtime() );
655 return (float)$st[0] + (float)$st[1];
659 * Changes the first character to an HTML entity
661 function wfHtmlEscapeFirst( $text ) {
662 $ord = ord($text);
663 $newText = substr($text, 1);
664 return "&#$ord;$newText";
668 * Sets dest to source and returns the original value of dest
669 * If source is NULL, it just returns the value, it doesn't set the variable
671 function wfSetVar( &$dest, $source ) {
672 $temp = $dest;
673 if ( !is_null( $source ) ) {
674 $dest = $source;
676 return $temp;
680 * As for wfSetVar except setting a bit
682 function wfSetBit( &$dest, $bit, $state = true ) {
683 $temp = (bool)($dest & $bit );
684 if ( !is_null( $state ) ) {
685 if ( $state ) {
686 $dest |= $bit;
687 } else {
688 $dest &= ~$bit;
691 return $temp;
695 * This function takes two arrays as input, and returns a CGI-style string, e.g.
696 * "days=7&limit=100". Options in the first array override options in the second.
697 * Options set to "" will not be output.
699 function wfArrayToCGI( $array1, $array2 = NULL )
701 if ( !is_null( $array2 ) ) {
702 $array1 = $array1 + $array2;
705 $cgi = '';
706 foreach ( $array1 as $key => $value ) {
707 if ( '' !== $value ) {
708 if ( '' != $cgi ) {
709 $cgi .= '&';
711 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
714 return $cgi;
718 * This is obsolete, use SquidUpdate::purge()
719 * @deprecated
721 function wfPurgeSquidServers ($urlArr) {
722 SquidUpdate::purge( $urlArr );
726 * Windows-compatible version of escapeshellarg()
727 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
728 * function puts single quotes in regardless of OS
730 function wfEscapeShellArg( ) {
731 $args = func_get_args();
732 $first = true;
733 $retVal = '';
734 foreach ( $args as $arg ) {
735 if ( !$first ) {
736 $retVal .= ' ';
737 } else {
738 $first = false;
741 if ( wfIsWindows() ) {
742 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
743 } else {
744 $retVal .= escapeshellarg( $arg );
747 return $retVal;
751 * wfMerge attempts to merge differences between three texts.
752 * Returns true for a clean merge and false for failure or a conflict.
754 function wfMerge( $old, $mine, $yours, &$result ){
755 global $wgDiff3;
757 # This check may also protect against code injection in
758 # case of broken installations.
759 if(! file_exists( $wgDiff3 ) ){
760 return false;
763 # Make temporary files
764 $td = '/tmp/';
765 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
766 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
767 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
769 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
770 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
771 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
773 # Check for a conflict
774 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
775 wfEscapeShellArg( $mytextName ) . ' ' .
776 wfEscapeShellArg( $oldtextName ) . ' ' .
777 wfEscapeShellArg( $yourtextName );
778 $handle = popen( $cmd, 'r' );
780 if( fgets( $handle ) ){
781 $conflict = true;
782 } else {
783 $conflict = false;
785 pclose( $handle );
787 # Merge differences
788 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
789 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
790 $handle = popen( $cmd, 'r' );
791 $result = '';
792 do {
793 $data = fread( $handle, 8192 );
794 if ( strlen( $data ) == 0 ) {
795 break;
797 $result .= $data;
798 } while ( true );
799 pclose( $handle );
800 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
801 return ! $conflict;
805 * @todo document
807 function wfVarDump( $var ) {
808 global $wgOut;
809 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
810 if ( headers_sent() || !@is_object( $wgOut ) ) {
811 print $s;
812 } else {
813 $wgOut->addHTML( $s );
818 * Provide a simple HTTP error.
820 function wfHttpError( $code, $label, $desc ) {
821 global $wgOut;
822 $wgOut->disable();
823 header( "HTTP/1.0 $code $label" );
824 header( "Status: $code $label" );
825 $wgOut->sendCacheControl();
827 # Don't send content if it's a HEAD request.
828 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
829 header( 'Content-type: text/plain' );
830 print "$desc\n";
835 * Converts an Accept-* header into an array mapping string values to quality
836 * factors
838 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
839 # No arg means accept anything (per HTTP spec)
840 if( !$accept ) {
841 return array( $def => 1 );
844 $prefs = array();
846 $parts = explode( ',', $accept );
848 foreach( $parts as $part ) {
849 # FIXME: doesn't deal with params like 'text/html; level=1'
850 @list( $value, $qpart ) = explode( ';', $part );
851 if( !isset( $qpart ) ) {
852 $prefs[$value] = 1;
853 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
854 $prefs[$value] = $match[1];
858 return $prefs;
862 * Checks if a given MIME type matches any of the keys in the given
863 * array. Basic wildcards are accepted in the array keys.
865 * Returns the matching MIME type (or wildcard) if a match, otherwise
866 * NULL if no match.
868 * @param string $type
869 * @param array $avail
870 * @return string
871 * @access private
873 function mimeTypeMatch( $type, $avail ) {
874 if( array_key_exists($type, $avail) ) {
875 return $type;
876 } else {
877 $parts = explode( '/', $type );
878 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
879 return $parts[0] . '/*';
880 } elseif( array_key_exists( '*/*', $avail ) ) {
881 return '*/*';
882 } else {
883 return NULL;
889 * Returns the 'best' match between a client's requested internet media types
890 * and the server's list of available types. Each list should be an associative
891 * array of type to preference (preference is a float between 0.0 and 1.0).
892 * Wildcards in the types are acceptable.
894 * @param array $cprefs Client's acceptable type list
895 * @param array $sprefs Server's offered types
896 * @return string
898 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
899 * XXX: generalize to negotiate other stuff
901 function wfNegotiateType( $cprefs, $sprefs ) {
902 $combine = array();
904 foreach( array_keys($sprefs) as $type ) {
905 $parts = explode( '/', $type );
906 if( $parts[1] != '*' ) {
907 $ckey = mimeTypeMatch( $type, $cprefs );
908 if( $ckey ) {
909 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
914 foreach( array_keys( $cprefs ) as $type ) {
915 $parts = explode( '/', $type );
916 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
917 $skey = mimeTypeMatch( $type, $sprefs );
918 if( $skey ) {
919 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
924 $bestq = 0;
925 $besttype = NULL;
927 foreach( array_keys( $combine ) as $type ) {
928 if( $combine[$type] > $bestq ) {
929 $besttype = $type;
930 $bestq = $combine[$type];
934 return $besttype;
938 * Array lookup
939 * Returns an array where the values in the first array are replaced by the
940 * values in the second array with the corresponding keys
942 * @return array
944 function wfArrayLookup( $a, $b ) {
945 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
949 * Convenience function; returns MediaWiki timestamp for the present time.
950 * @return string
952 function wfTimestampNow() {
953 # return NOW
954 return wfTimestamp( TS_MW, time() );
958 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
960 function wfInvertTimestamp( $ts ) {
961 return strtr(
962 $ts,
963 '0123456789',
964 '9876543210'
969 * Reference-counted warning suppression
971 function wfSuppressWarnings( $end = false ) {
972 static $suppressCount = 0;
973 static $originalLevel = false;
975 if ( $end ) {
976 if ( $suppressCount ) {
977 $suppressCount --;
978 if ( !$suppressCount ) {
979 error_reporting( $originalLevel );
982 } else {
983 if ( !$suppressCount ) {
984 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
986 $suppressCount++;
991 * Restore error level to previous value
993 function wfRestoreWarnings() {
994 wfSuppressWarnings( true );
997 # Autodetect, convert and provide timestamps of various types
999 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
1000 define('TS_UNIX',0);
1001 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
1002 define('TS_MW',1);
1003 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
1004 define('TS_DB',2);
1007 * @todo document
1009 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1010 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1011 # TS_DB
1012 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1013 (int)$da[2],(int)$da[3],(int)$da[1]);
1014 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1015 # TS_MW
1016 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1017 (int)$da[2],(int)$da[3],(int)$da[1]);
1018 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1019 # TS_UNIX
1020 $uts=$ts;
1023 if ($ts==0)
1024 $uts=time();
1025 switch($outputtype) {
1026 case TS_UNIX:
1027 return $uts;
1028 break;
1029 case TS_MW:
1030 return gmdate( 'YmdHis', $uts );
1031 break;
1032 case TS_DB:
1033 return gmdate( 'Y-m-d H:i:s', $uts );
1034 break;
1035 default:
1036 return;
1041 * Check where as the operating system is Windows
1043 * @todo document
1044 * @return bool True if it's windows, False otherwise.
1046 function wfIsWindows() {
1047 if (substr(php_uname(), 0, 7) == 'Windows') {
1048 return true;
1049 } else {
1050 return false;