* Select the content language in prefs when bogus interface language is set
[mediawiki.git] / includes / GlobalFunctions.php
blobe06835174c308526e8a5576541cdfc1f238bbd78
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( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
34 /**
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
48 return $string;
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
62 return
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
76 } else {
77 return join( '', array_slice( $ar[0], $start ) );
82 /**
83 * html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
84 * with no UTF-8 support.
86 * @param string $string String having html entities
87 * @param $quote_style
88 * @param string $charset Encoding set to use (default 'ISO-8859-1')
90 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT, $charset='ISO-8859-1' ) {
91 $fname = 'do_html_entity_decode';
92 wfProfileIn( $fname );
94 static $trans;
95 static $savedCharset;
96 static $regexp;
97 if( !isset( $trans ) || $savedCharset != $charset ) {
98 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
99 $savedCharset = $charset;
101 # Note - mixing latin1 named entities and unicode numbered
102 # ones will result in a bad link.
103 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
104 $trans = array_map( 'utf8_encode', $trans );
108 * Most links will _not_ contain these fun guys,
109 * and on long pages with many links we can get
110 * called a lot.
112 * A regular expression search is faster than
113 * a strtr or str_replace with a hundred-ish
114 * entries, though it may be slower to actually
115 * replace things.
117 * They all look like '&xxxx;'...
119 foreach( $trans as $key => $val ) {
120 $snip[] = substr( $key, 1, -1 );
122 $regexp = '/(&(?:' . implode( '|', $snip ) . ');)/e';
125 $out = preg_replace( $regexp, '$trans["$1"]', $string );
126 wfProfileOut( $fname );
127 return $out;
132 * Where as we got a random seed
133 * @var bool $wgTotalViews
135 $wgRandomSeeded = false;
138 * Seed Mersenne Twister
139 * Only necessary in PHP < 4.2.0
141 * @return bool
143 function wfSeedRandom() {
144 global $wgRandomSeeded;
146 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
147 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
148 mt_srand( $seed );
149 $wgRandomSeeded = true;
154 * Get a random decimal value between 0 and 1, in a way
155 * not likely to give duplicate values for any realistic
156 * number of articles.
158 * @return string
160 function wfRandom() {
161 # The maximum random value is "only" 2^31-1, so get two random
162 # values to reduce the chance of dupes
163 $max = mt_getrandmax();
164 $rand = number_format( mt_rand() * mt_rand()
165 / $max / $max, 12, '.', '' );
166 return $rand;
170 * We want / and : to be included as literal characters in our title URLs.
171 * %2F in the page titles seems to fatally break for some reason.
173 * @param string $s
174 * @return string
176 function wfUrlencode ( $s ) {
177 $s = urlencode( $s );
178 $s = preg_replace( '/%3[Aa]/', ':', $s );
179 $s = preg_replace( '/%2[Ff]/', '/', $s );
181 return $s;
185 * Return the UTF-8 sequence for a given Unicode code point.
186 * Currently doesn't work for values outside the Basic Multilingual Plane.
188 * @param string $codepoint UTF-8 code point.
189 * @return string HTML UTF-8 Entitie such as '&#1234;'.
191 function wfUtf8Sequence( $codepoint ) {
192 if($codepoint < 0x80) return chr($codepoint);
193 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
194 chr($codepoint & 0x3f | 0x80);
195 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
196 chr($codepoint >> 6 & 0x3f | 0x80) .
197 chr($codepoint & 0x3f | 0x80);
198 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 | 0xf0) .
199 chr($codepoint >> 12 & 0x3f | 0x80) .
200 chr($codepoint >> 6 & 0x3f | 0x80) .
201 chr($codepoint & 0x3f | 0x80);
203 # There should be no assigned code points outside this range, but...
204 return "&#$codepoint;";
208 * Converts numeric character entities to UTF-8
210 * @param string $string String to convert.
211 * @return string Converted string.
213 function wfMungeToUtf8( $string ) {
214 global $wgInputEncoding; # This is debatable
215 #$string = iconv($wgInputEncoding, "UTF-8", $string);
216 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
217 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
218 # Should also do named entities here
219 return $string;
223 * Converts a single UTF-8 character into the corresponding HTML character
224 * entity (for use with preg_replace_callback)
226 * @param array $matches
229 function wfUtf8Entity( $matches ) {
230 $codepoint = utf8ToCodepoint( $matches[0] );
231 return "&#$codepoint;";
235 * Converts all multi-byte characters in a UTF-8 string into the appropriate
236 * character entity
238 function wfUtf8ToHTML($string) {
239 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
243 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
244 * In normal operation this is a NOP.
246 * Controlling globals:
247 * $wgDebugLogFile - points to the log file
248 * $wgProfileOnly - if set, normal debug messages will not be recorded.
249 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
250 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
252 * @param string $text
253 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
255 function wfDebug( $text, $logonly = false ) {
256 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
258 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
259 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
260 return;
263 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
264 $wgOut->debug( $text );
266 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
267 error_log( $text, 3, $wgDebugLogFile );
272 * Log for database errors
273 * @param string $text Database error message.
275 function wfLogDBError( $text ) {
276 global $wgDBerrorLog;
277 if ( $wgDBerrorLog ) {
278 $text = date('D M j G:i:s T Y') . "\t".$text;
279 error_log( $text, 3, $wgDBerrorLog );
284 * @todo document
286 function logProfilingData() {
287 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
288 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
289 $now = wfTime();
291 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
292 $start = (float)$sec + (float)$usec;
293 $elapsed = $now - $start;
294 if ( $wgProfiling ) {
295 $prof = wfGetProfilingOutput( $start, $elapsed );
296 $forward = '';
297 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
298 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
299 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
300 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
301 if( !empty( $_SERVER['HTTP_FROM'] ) )
302 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
303 if( $forward )
304 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
305 if($wgUser->getId() == 0)
306 $forward .= ' anon';
307 $log = sprintf( "%s\t%04.3f\t%s\n",
308 gmdate( 'YmdHis' ), $elapsed,
309 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
310 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
311 error_log( $log . $prof, 3, $wgDebugLogFile );
317 * Check if the wiki read-only lock file is present. This can be used to lock
318 * off editing functions, but doesn't guarantee that the database will not be
319 * modified.
320 * @return bool
322 function wfReadOnly() {
323 global $wgReadOnlyFile;
325 if ( '' == $wgReadOnlyFile ) {
326 return false;
328 return is_file( $wgReadOnlyFile );
333 * Get a message from anywhere, for the UI elements
335 function wfMsg( $key ) {
336 $args = func_get_args();
337 array_shift( $args );
338 return wfMsgReal( $key, $args, true );
342 * Get a message from anywhere, for the content
344 function wfMsgForContent( $key ) {
345 global $wgForceUIMsgAsContentMsg;
346 $args = func_get_args();
347 array_shift( $args );
348 $forcontent = true;
349 if( is_array( $wgForceUIMsgAsContentMsg ) &&
350 in_array( $key, $wgForceUIMsgAsContentMsg ) )
351 $forcontent = false;
352 return wfMsgReal( $key, $args, true, $forcontent );
356 * Get a message from the language file, for the UI elements
358 function wfMsgNoDB( $key ) {
359 $args = func_get_args();
360 array_shift( $args );
361 return wfMsgReal( $key, $args, false );
365 * Get a message from the language file, for the content
367 function wfMsgNoDBForContent( $key ) {
368 global $wgForceUIMsgAsContentMsg;
369 $args = func_get_args();
370 array_shift( $args );
371 $forcontent = true;
372 if( is_array( $wgForceUIMsgAsContentMsg ) &&
373 in_array( $key, $wgForceUIMsgAsContentMsg ) )
374 $forcontent = false;
375 return wfMsgReal( $key, $args, false, $forcontent );
380 * Really get a message
382 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
383 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
384 global $wgParser, $wgMsgParserOptions;
385 global $wgContLang, $wgLanguageCode;
386 global $wgMessageCache, $wgLang;
388 $fname = 'wfMsgReal';
389 wfProfileIn( $fname );
391 if( is_object( $wgMessageCache ) ) {
392 $message = $wgMessageCache->get( $key, $useDB, $forContent );
394 else {
395 if( $forContent ) {
396 $lang = &$wgContLang;
397 } else {
398 $lang = &$wgLang;
401 wfSuppressWarnings();
402 $message = $lang->getMessage( $key );
403 wfRestoreWarnings();
404 if(!$message)
405 $message = Language::getMessage($key);
406 if(strstr($message, '{{' ) !== false) {
407 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
411 # Replace arguments
412 if( count( $args ) ) {
413 $message = str_replace( $replacementKeys, $args, $message );
415 wfProfileOut( $fname );
416 return $message;
422 * Just like exit() but makes a note of it.
423 * Commits open transactions except if the error parameter is set
425 function wfAbruptExit( $error = false ){
426 global $wgLoadBalancer;
427 static $called = false;
428 if ( $called ){
429 exit();
431 $called = true;
433 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
434 $bt = debug_backtrace();
435 for($i = 0; $i < count($bt) ; $i++){
436 $file = $bt[$i]['file'];
437 $line = $bt[$i]['line'];
438 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
440 } else {
441 wfDebug('WARNING: Abrupt exit\n');
443 if ( !$error ) {
444 $wgLoadBalancer->closeAll();
446 exit();
450 * @todo document
452 function wfErrorExit() {
453 wfAbruptExit( true );
457 * Die with a backtrace
458 * This is meant as a debugging aid to track down where bad data comes from.
459 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
461 * @param string $msg Message shown when dieing.
463 function wfDebugDieBacktrace( $msg = '' ) {
464 global $wgCommandLineMode;
466 if ( function_exists( 'debug_backtrace' ) ) {
467 if ( $wgCommandLineMode ) {
468 $msg .= "\nBacktrace:\n";
469 } else {
470 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
472 $backtrace = debug_backtrace();
473 foreach( $backtrace as $call ) {
474 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
475 $file = $f[count($f)-1];
476 if ( $wgCommandLineMode ) {
477 $msg .= "$file line {$call['line']} calls ";
478 } else {
479 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
481 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
482 $msg .= $call['function'] . '()';
484 if ( $wgCommandLineMode ) {
485 $msg .= "\n";
486 } else {
487 $msg .= "</li>\n";
491 die( $msg );
495 /* Some generic result counters, pulled out of SearchEngine */
499 * @todo document
501 function wfShowingResults( $offset, $limit ) {
502 global $wgLang;
503 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
507 * @todo document
509 function wfShowingResultsNum( $offset, $limit, $num ) {
510 global $wgLang;
511 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
515 * @todo document
517 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
518 global $wgUser, $wgLang;
519 $fmtLimit = $wgLang->formatNum( $limit );
520 $prev = wfMsg( 'prevn', $fmtLimit );
521 $next = wfMsg( 'nextn', $fmtLimit );
523 if( is_object( $link ) ) {
524 $title =& $link;
525 } else {
526 $title =& Title::newFromText( $link );
527 if( is_null( $title ) ) {
528 return false;
532 $sk = $wgUser->getSkin();
533 if ( 0 != $offset ) {
534 $po = $offset - $limit;
535 if ( $po < 0 ) { $po = 0; }
536 $q = "limit={$limit}&offset={$po}";
537 if ( '' != $query ) { $q .= '&'.$query; }
538 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
539 } else { $plink = $prev; }
541 $no = $offset + $limit;
542 $q = 'limit='.$limit.'&offset='.$no;
543 if ( '' != $query ) { $q .= '&'.$query; }
545 if ( $atend ) {
546 $nlink = $next;
547 } else {
548 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
550 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
551 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
552 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
553 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
554 wfNumLink( $offset, 500, $title, $query );
556 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
560 * @todo document
562 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
563 global $wgUser, $wgLang;
564 if ( '' == $query ) { $q = ''; }
565 else { $q = $query.'&'; }
566 $q .= 'limit='.$limit.'&offset='.$offset;
568 $fmtLimit = $wgLang->formatNum( $limit );
569 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
570 return $s;
574 * @todo document
575 * @todo FIXME: we may want to blacklist some broken browsers
577 * @return bool Whereas client accept gzip compression
579 function wfClientAcceptsGzip() {
580 global $wgUseGzip;
581 if( $wgUseGzip ) {
582 # FIXME: we may want to blacklist some broken browsers
583 if( preg_match(
584 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
585 $_SERVER['HTTP_ACCEPT_ENCODING'],
586 $m ) ) {
587 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
588 wfDebug( " accepts gzip\n" );
589 return true;
592 return false;
596 * Yay, more global functions!
598 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
599 global $wgRequest;
600 return $wgRequest->getLimitOffset( $deflimit, $optionname );
604 * Escapes the given text so that it may be output using addWikiText()
605 * without any linking, formatting, etc. making its way through. This
606 * is achieved by substituting certain characters with HTML entities.
607 * As required by the callers, <nowiki> is not used. It currently does
608 * not filter out characters which have special meaning only at the
609 * start of a line, such as "*".
611 * @param string $text Text to be escaped
613 function wfEscapeWikiText( $text ) {
614 $text = str_replace(
615 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
616 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
617 htmlspecialchars($text) );
618 return $text;
622 * @todo document
624 function wfQuotedPrintable( $string, $charset = '' ) {
625 # Probably incomplete; see RFC 2045
626 if( empty( $charset ) ) {
627 global $wgInputEncoding;
628 $charset = $wgInputEncoding;
630 $charset = strtoupper( $charset );
631 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
633 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
634 $replace = $illegal . '\t ?_';
635 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
636 $out = "=?$charset?Q?";
637 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
638 $out .= '?=';
639 return $out;
643 * @todo document
644 * @return float
646 function wfTime() {
647 $st = explode( ' ', microtime() );
648 return (float)$st[0] + (float)$st[1];
652 * Changes the first character to an HTML entity
654 function wfHtmlEscapeFirst( $text ) {
655 $ord = ord($text);
656 $newText = substr($text, 1);
657 return "&#$ord;$newText";
661 * Sets dest to source and returns the original value of dest
662 * If source is NULL, it just returns the value, it doesn't set the variable
664 function wfSetVar( &$dest, $source ) {
665 $temp = $dest;
666 if ( !is_null( $source ) ) {
667 $dest = $source;
669 return $temp;
673 * As for wfSetVar except setting a bit
675 function wfSetBit( &$dest, $bit, $state = true ) {
676 $temp = (bool)($dest & $bit );
677 if ( !is_null( $state ) ) {
678 if ( $state ) {
679 $dest |= $bit;
680 } else {
681 $dest &= ~$bit;
684 return $temp;
688 * This function takes two arrays as input, and returns a CGI-style string, e.g.
689 * "days=7&limit=100". Options in the first array override options in the second.
690 * Options set to "" will not be output.
692 function wfArrayToCGI( $array1, $array2 = NULL )
694 if ( !is_null( $array2 ) ) {
695 $array1 = $array1 + $array2;
698 $cgi = '';
699 foreach ( $array1 as $key => $value ) {
700 if ( '' !== $value ) {
701 if ( '' != $cgi ) {
702 $cgi .= '&';
704 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
707 return $cgi;
711 * This is obsolete, use SquidUpdate::purge()
712 * @deprecated
714 function wfPurgeSquidServers ($urlArr) {
715 SquidUpdate::purge( $urlArr );
719 * Windows-compatible version of escapeshellarg()
720 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
721 * function puts single quotes in regardless of OS
723 function wfEscapeShellArg( ) {
724 $args = func_get_args();
725 $first = true;
726 $retVal = '';
727 foreach ( $args as $arg ) {
728 if ( !$first ) {
729 $retVal .= ' ';
730 } else {
731 $first = false;
734 if ( wfIsWindows() ) {
735 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
736 } else {
737 $retVal .= escapeshellarg( $arg );
740 return $retVal;
744 * wfMerge attempts to merge differences between three texts.
745 * Returns true for a clean merge and false for failure or a conflict.
747 function wfMerge( $old, $mine, $yours, &$result ){
748 global $wgDiff3;
750 # This check may also protect against code injection in
751 # case of broken installations.
752 if(! file_exists( $wgDiff3 ) ){
753 return false;
756 # Make temporary files
757 $td = '/tmp/';
758 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
759 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
760 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
762 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
763 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
764 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
766 # Check for a conflict
767 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
768 wfEscapeShellArg( $mytextName ) . ' ' .
769 wfEscapeShellArg( $oldtextName ) . ' ' .
770 wfEscapeShellArg( $yourtextName );
771 $handle = popen( $cmd, 'r' );
773 if( fgets( $handle ) ){
774 $conflict = true;
775 } else {
776 $conflict = false;
778 pclose( $handle );
780 # Merge differences
781 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
782 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
783 $handle = popen( $cmd, 'r' );
784 $result = '';
785 do {
786 $data = fread( $handle, 8192 );
787 if ( strlen( $data ) == 0 ) {
788 break;
790 $result .= $data;
791 } while ( true );
792 pclose( $handle );
793 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
794 return ! $conflict;
798 * @todo document
800 function wfVarDump( $var ) {
801 global $wgOut;
802 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
803 if ( headers_sent() || !@is_object( $wgOut ) ) {
804 print $s;
805 } else {
806 $wgOut->addHTML( $s );
811 * Provide a simple HTTP error.
813 function wfHttpError( $code, $label, $desc ) {
814 global $wgOut;
815 $wgOut->disable();
816 header( "HTTP/1.0 $code $label" );
817 header( "Status: $code $label" );
818 $wgOut->sendCacheControl();
820 # Don't send content if it's a HEAD request.
821 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
822 header( 'Content-type: text/plain' );
823 print "$desc\n";
828 * Converts an Accept-* header into an array mapping string values to quality
829 * factors
831 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
832 # No arg means accept anything (per HTTP spec)
833 if( !$accept ) {
834 return array( $def => 1 );
837 $prefs = array();
839 $parts = explode( ',', $accept );
841 foreach( $parts as $part ) {
842 # FIXME: doesn't deal with params like 'text/html; level=1'
843 @list( $value, $qpart ) = explode( ';', $part );
844 if( !isset( $qpart ) ) {
845 $prefs[$value] = 1;
846 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
847 $prefs[$value] = $match[1];
851 return $prefs;
855 * Checks if a given MIME type matches any of the keys in the given
856 * array. Basic wildcards are accepted in the array keys.
858 * Returns the matching MIME type (or wildcard) if a match, otherwise
859 * NULL if no match.
861 * @param string $type
862 * @param array $avail
863 * @return string
864 * @access private
866 function mimeTypeMatch( $type, $avail ) {
867 if( array_key_exists($type, $avail) ) {
868 return $type;
869 } else {
870 $parts = explode( '/', $type );
871 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
872 return $parts[0] . '/*';
873 } elseif( array_key_exists( '*/*', $avail ) ) {
874 return '*/*';
875 } else {
876 return NULL;
882 * Returns the 'best' match between a client's requested internet media types
883 * and the server's list of available types. Each list should be an associative
884 * array of type to preference (preference is a float between 0.0 and 1.0).
885 * Wildcards in the types are acceptable.
887 * @param array $cprefs Client's acceptable type list
888 * @param array $sprefs Server's offered types
889 * @return string
891 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
892 * XXX: generalize to negotiate other stuff
894 function wfNegotiateType( $cprefs, $sprefs ) {
895 $combine = array();
897 foreach( array_keys($sprefs) as $type ) {
898 $parts = explode( '/', $type );
899 if( $parts[1] != '*' ) {
900 $ckey = mimeTypeMatch( $type, $cprefs );
901 if( $ckey ) {
902 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
907 foreach( array_keys( $cprefs ) as $type ) {
908 $parts = explode( '/', $type );
909 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
910 $skey = mimeTypeMatch( $type, $sprefs );
911 if( $skey ) {
912 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
917 $bestq = 0;
918 $besttype = NULL;
920 foreach( array_keys( $combine ) as $type ) {
921 if( $combine[$type] > $bestq ) {
922 $besttype = $type;
923 $bestq = $combine[$type];
927 return $besttype;
931 * Array lookup
932 * Returns an array where the values in the first array are replaced by the
933 * values in the second array with the corresponding keys
935 * @return array
937 function wfArrayLookup( $a, $b ) {
938 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
942 * Convenience function; returns MediaWiki timestamp for the present time.
943 * @return string
945 function wfTimestampNow() {
946 # return NOW
947 return wfTimestamp( TS_MW, time() );
951 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
953 function wfInvertTimestamp( $ts ) {
954 return strtr(
955 $ts,
956 '0123456789',
957 '9876543210'
962 * Reference-counted warning suppression
964 function wfSuppressWarnings( $end = false ) {
965 static $suppressCount = 0;
966 static $originalLevel = false;
968 if ( $end ) {
969 if ( $suppressCount ) {
970 $suppressCount --;
971 if ( !$suppressCount ) {
972 error_reporting( $originalLevel );
975 } else {
976 if ( !$suppressCount ) {
977 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
979 $suppressCount++;
984 * Restore error level to previous value
986 function wfRestoreWarnings() {
987 wfSuppressWarnings( true );
990 # Autodetect, convert and provide timestamps of various types
992 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
993 define('TS_UNIX',0);
994 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
995 define('TS_MW',1);
996 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
997 define('TS_DB',2);
998 /** For HTTP and e-mail headers -- output only */
999 define('TS_RFC2822', 3 );
1002 * @todo document
1004 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1005 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1006 # TS_DB
1007 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1008 (int)$da[2],(int)$da[3],(int)$da[1]);
1009 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1010 # TS_MW
1011 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1012 (int)$da[2],(int)$da[3],(int)$da[1]);
1013 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1014 # TS_UNIX
1015 $uts=$ts;
1018 if ($ts==0)
1019 $uts=time();
1020 switch($outputtype) {
1021 case TS_UNIX:
1022 return $uts;
1023 case TS_MW:
1024 return gmdate( 'YmdHis', $uts );
1025 case TS_DB:
1026 return gmdate( 'Y-m-d H:i:s', $uts );
1027 case TS_RFC2822:
1028 return gmdate( "D, j M Y H:i:s", $uts ) . ' GMT';
1029 default:
1030 return;
1035 * Check where as the operating system is Windows
1037 * @todo document
1038 * @return bool True if it's windows, False otherwise.
1040 function wfIsWindows() {
1041 if (substr(php_uname(), 0, 7) == 'Windows') {
1042 return true;
1043 } else {
1044 return false;