Updated the checktrans.php script to be a little more modern and to
[mediawiki.git] / includes / GlobalFunctions.php
blob971e671db9429d93fc4a05117dba269f7b930e1f
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' );
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 static $trans;
92 if( !isset( $trans ) ) {
93 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
94 # Assumes $charset will always be the same through a run, and only understands
95 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
96 # ones will result in a bad link.
97 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
98 $trans = array_map( 'utf8_encode', $trans );
101 return strtr( $string, $trans );
106 * Where as we got a random seed
107 * @var bool $wgTotalViews
109 $wgRandomSeeded = false;
112 * Seed Mersenne Twister
113 * Only necessary in PHP < 4.2.0
115 * @return bool
117 function wfSeedRandom() {
118 global $wgRandomSeeded;
120 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
121 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
122 mt_srand( $seed );
123 $wgRandomSeeded = true;
128 * We want / and : to be included as literal characters in our title URLs.
129 * %2F in the page titles seems to fatally break for some reason.
131 * @param string $s
132 * @return string
134 function wfUrlencode ( $s ) {
135 $s = urlencode( $s );
136 $s = preg_replace( '/%3[Aa]/', ':', $s );
137 $s = preg_replace( '/%2[Ff]/', '/', $s );
139 return $s;
143 * Return the UTF-8 sequence for a given Unicode code point.
144 * Currently doesn't work for values outside the Basic Multilingual Plane.
146 * @param string $codepoint UTF-8 code point.
147 * @return string HTML UTF-8 Entitie such as '&#1234;'.
149 function wfUtf8Sequence( $codepoint ) {
150 if($codepoint < 0x80) return chr($codepoint);
151 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
152 chr($codepoint & 0x3f | 0x80);
153 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
154 chr($codepoint >> 6 & 0x3f | 0x80) .
155 chr($codepoint & 0x3f | 0x80);
156 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 | 0xf0) .
157 chr($codepoint >> 12 & 0x3f | 0x80) .
158 chr($codepoint >> 6 & 0x3f | 0x80) .
159 chr($codepoint & 0x3f | 0x80);
161 # There should be no assigned code points outside this range, but...
162 return "&#$codepoint;";
166 * Converts numeric character entities to UTF-8
168 * @param string $string String to convert.
169 * @return string Converted string.
171 function wfMungeToUtf8( $string ) {
172 global $wgInputEncoding; # This is debatable
173 #$string = iconv($wgInputEncoding, "UTF-8", $string);
174 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
175 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
176 # Should also do named entities here
177 return $string;
181 * Converts a single UTF-8 character into the corresponding HTML character
182 * entity (for use with preg_replace_callback)
184 * @param array $matches
187 function wfUtf8Entity( $matches ) {
188 $codepoint = utf8ToCodepoint( $matches[0] );
189 return "&#$codepoint;";
193 * Converts all multi-byte characters in a UTF-8 string into the appropriate
194 * character entity
196 function wfUtf8ToHTML($string) {
197 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
201 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
202 * In normal operation this is a NOP.
204 * Controlling globals:
205 * $wgDebugLogFile - points to the log file
206 * $wgProfileOnly - if set, normal debug messages will not be recorded.
207 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
208 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
210 * @param string $text
211 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
213 function wfDebug( $text, $logonly = false ) {
214 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
216 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
217 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
218 return;
221 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
222 $wgOut->debug( $text );
224 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
225 error_log( $text, 3, $wgDebugLogFile );
230 * Log for database errors
231 * @param string $text Database error message.
233 function wfLogDBError( $text ) {
234 global $wgDBerrorLog;
235 if ( $wgDBerrorLog ) {
236 $text = date('D M j G:i:s T Y') . "\t".$text;
237 error_log( $text, 3, $wgDBerrorLog );
242 * @todo document
244 function logProfilingData() {
245 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
246 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
247 $now = wfTime();
249 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
250 $start = (float)$sec + (float)$usec;
251 $elapsed = $now - $start;
252 if ( $wgProfiling ) {
253 $prof = wfGetProfilingOutput( $start, $elapsed );
254 $forward = '';
255 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
256 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
257 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
258 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
259 if( !empty( $_SERVER['HTTP_FROM'] ) )
260 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
261 if( $forward )
262 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
263 if($wgUser->getId() == 0)
264 $forward .= ' anon';
265 $log = sprintf( "%s\t%04.3f\t%s\n",
266 gmdate( 'YmdHis' ), $elapsed,
267 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
268 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
269 error_log( $log . $prof, 3, $wgDebugLogFile );
275 * Check if the wiki read-only lock file is present. This can be used to lock
276 * off editing functions, but doesn't guarantee that the database will not be
277 * modified.
278 * @return bool
280 function wfReadOnly() {
281 global $wgReadOnlyFile;
283 if ( '' == $wgReadOnlyFile ) {
284 return false;
286 return is_file( $wgReadOnlyFile );
291 * Get a message from anywhere, for the UI elements
293 function wfMsg( $key ) {
294 global $wgRequest;
296 if ( $wgRequest->getVal( 'debugmsg' ) ) {
297 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
298 return "/^()(.*)$/sD";
299 else
300 return $key;
302 $args = func_get_args();
303 if ( count( $args ) ) {
304 array_shift( $args );
306 return wfMsgReal( $key, $args, true );
310 * Get a message from anywhere, for the content
312 function wfMsgForContent( $key ) {
313 global $wgRequest;
314 if ( $wgRequest->getVal( 'debugmsg' ) ) {
315 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
316 return "/^()(.*)$/sD";
317 else
318 return $key;
320 $args = func_get_args();
321 if ( count( $args ) ) {
322 array_shift( $args );
324 return wfMsgReal( $key, $args, true, true );
330 * Get a message from the language file, for the UI elements
332 function wfMsgNoDB( $key ) {
333 $args = func_get_args();
334 if ( count( $args ) ) {
335 array_shift( $args );
337 return wfMsgReal( $key, $args, false );
341 * Get a message from the language file, for the content
343 function wfMsgNoDBForContent( $key ) {
345 $args = func_get_args();
346 if ( count( $args ) ) {
347 array_shift( $args );
349 return wfMsgReal( $key, $args, false, true );
354 * Really get a message
356 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
357 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
358 global $wgParser, $wgMsgParserOptions;
359 global $wgContLang, $wgLanguageCode;
360 if($forContent) {
361 global $wgMessageCache;
362 $cache = &$wgMessageCache;
363 $lang = &$wgContLang;
365 else {
366 if(in_array($wgLanguageCode, $wgContLang->getVariants())){
367 global $wgLang, $wgMessageCache;
368 $cache = &$wgMessageCache;
369 $lang = $wgLang;
371 else {
372 global $wgLang;
373 $cache = false;
374 $lang = &$wgLang;
378 $fname = 'wfMsg';
379 wfProfileIn( $fname );
380 if ( is_object($cache) ) {
381 $message = $cache->get( $key, $useDB, $forContent );
382 } elseif (is_object($lang)) {
383 $message = $lang->getMessage( $key );
384 if(!$message)
385 $message = Language::getMessage($key);
386 if(strstr($message, '{{' ) !== false) {
387 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
389 } else {
390 wfDebug( "No language object when getting $key\n" );
391 $message = "&lt;$key&gt;";
394 # Replace arguments
395 if( count( $args ) ) {
396 $message = str_replace( $replacementKeys, $args, $message );
398 wfProfileOut( $fname );
399 return $message;
405 * Just like exit() but makes a note of it.
406 * Commits open transactions except if the error parameter is set
408 function wfAbruptExit( $error = false ){
409 global $wgLoadBalancer;
410 static $called = false;
411 if ( $called ){
412 exit();
414 $called = true;
416 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
417 $bt = debug_backtrace();
418 for($i = 0; $i < count($bt) ; $i++){
419 $file = $bt[$i]['file'];
420 $line = $bt[$i]['line'];
421 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
423 } else {
424 wfDebug('WARNING: Abrupt exit\n');
426 if ( !$error ) {
427 $wgLoadBalancer->closeAll();
429 exit();
433 * @todo document
435 function wfErrorExit() {
436 wfAbruptExit( true );
440 * Die with a backtrace
441 * This is meant as a debugging aid to track down where bad data comes from.
442 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
444 * @param string $msg Message shown when dieing.
446 function wfDebugDieBacktrace( $msg = '' ) {
447 global $wgCommandLineMode;
449 if ( function_exists( 'debug_backtrace' ) ) {
450 if ( $wgCommandLineMode ) {
451 $msg .= "\nBacktrace:\n";
452 } else {
453 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
455 $backtrace = debug_backtrace();
456 foreach( $backtrace as $call ) {
457 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
458 $file = $f[count($f)-1];
459 if ( $wgCommandLineMode ) {
460 $msg .= "$file line {$call['line']} calls ";
461 } else {
462 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
464 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
465 $msg .= $call['function'] . '()';
467 if ( $wgCommandLineMode ) {
468 $msg .= "\n";
469 } else {
470 $msg .= "</li>\n";
474 die( $msg );
478 /* Some generic result counters, pulled out of SearchEngine */
482 * @todo document
484 function wfShowingResults( $offset, $limit ) {
485 global $wgLang;
486 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
490 * @todo document
492 function wfShowingResultsNum( $offset, $limit, $num ) {
493 global $wgLang;
494 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
498 * @todo document
500 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
501 global $wgUser, $wgLang;
502 $fmtLimit = $wgLang->formatNum( $limit );
503 $prev = wfMsg( 'prevn', $fmtLimit );
504 $next = wfMsg( 'nextn', $fmtLimit );
506 if( is_object( $link ) ) {
507 $title =& $link;
508 } else {
509 $title =& Title::newFromText( $link );
510 if( is_null( $title ) ) {
511 return false;
515 $sk = $wgUser->getSkin();
516 if ( 0 != $offset ) {
517 $po = $offset - $limit;
518 if ( $po < 0 ) { $po = 0; }
519 $q = "limit={$limit}&offset={$po}";
520 if ( '' != $query ) { $q .= '&'.$query; }
521 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
522 } else { $plink = $prev; }
524 $no = $offset + $limit;
525 $q = 'limit='.$limit.'&offset='.$no;
526 if ( '' != $query ) { $q .= '&'.$query; }
528 if ( $atend ) {
529 $nlink = $next;
530 } else {
531 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
533 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
534 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
535 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
536 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
537 wfNumLink( $offset, 500, $title, $query );
539 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
543 * @todo document
545 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
546 global $wgUser, $wgLang;
547 if ( '' == $query ) { $q = ''; }
548 else { $q = $query.'&'; }
549 $q .= 'limit='.$limit.'&offset='.$offset;
551 $fmtLimit = $wgLang->formatNum( $limit );
552 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
553 return $s;
557 * @todo document
558 * @todo FIXME: we may want to blacklist some broken browsers
560 * @return bool Whereas client accept gzip compression
562 function wfClientAcceptsGzip() {
563 global $wgUseGzip;
564 if( $wgUseGzip ) {
565 # FIXME: we may want to blacklist some broken browsers
566 if( preg_match(
567 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
568 $_SERVER['HTTP_ACCEPT_ENCODING'],
569 $m ) ) {
570 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
571 wfDebug( " accepts gzip\n" );
572 return true;
575 return false;
579 * Yay, more global functions!
581 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
582 global $wgRequest;
583 return $wgRequest->getLimitOffset( $deflimit, $optionname );
587 * Escapes the given text so that it may be output using addWikiText()
588 * without any linking, formatting, etc. making its way through. This
589 * is achieved by substituting certain characters with HTML entities.
590 * As required by the callers, <nowiki> is not used. It currently does
591 * not filter out characters which have special meaning only at the
592 * start of a line, such as "*".
594 * @param string $text Text to be escaped
596 function wfEscapeWikiText( $text ) {
597 $text = str_replace(
598 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
599 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
600 htmlspecialchars($text) );
601 return $text;
605 * @todo document
607 function wfQuotedPrintable( $string, $charset = '' ) {
608 # Probably incomplete; see RFC 2045
609 if( empty( $charset ) ) {
610 global $wgInputEncoding;
611 $charset = $wgInputEncoding;
613 $charset = strtoupper( $charset );
614 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
616 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
617 $replace = $illegal . '\t ?_';
618 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
619 $out = "=?$charset?Q?";
620 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
621 $out .= '?=';
622 return $out;
626 * @todo document
627 * @return float
629 function wfTime() {
630 $st = explode( ' ', microtime() );
631 return (float)$st[0] + (float)$st[1];
635 * Changes the first character to an HTML entity
637 function wfHtmlEscapeFirst( $text ) {
638 $ord = ord($text);
639 $newText = substr($text, 1);
640 return "&#$ord;$newText";
644 * Sets dest to source and returns the original value of dest
645 * If source is NULL, it just returns the value, it doesn't set the variable
647 function wfSetVar( &$dest, $source ) {
648 $temp = $dest;
649 if ( !is_null( $source ) ) {
650 $dest = $source;
652 return $temp;
656 * As for wfSetVar except setting a bit
658 function wfSetBit( &$dest, $bit, $state = true ) {
659 $temp = (bool)($dest & $bit );
660 if ( !is_null( $state ) ) {
661 if ( $state ) {
662 $dest |= $bit;
663 } else {
664 $dest &= ~$bit;
667 return $temp;
671 * This function takes two arrays as input, and returns a CGI-style string, e.g.
672 * "days=7&limit=100". Options in the first array override options in the second.
673 * Options set to "" will not be output.
675 function wfArrayToCGI( $array1, $array2 = NULL )
677 if ( !is_null( $array2 ) ) {
678 $array1 = $array1 + $array2;
681 $cgi = '';
682 foreach ( $array1 as $key => $value ) {
683 if ( '' !== $value ) {
684 if ( '' != $cgi ) {
685 $cgi .= '&';
687 $cgi .= $key.'='.$value;
690 return $cgi;
694 * This is obsolete, use SquidUpdate::purge()
695 * @deprecated
697 function wfPurgeSquidServers ($urlArr) {
698 SquidUpdate::purge( $urlArr );
702 * Windows-compatible version of escapeshellarg()
703 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
704 * function puts single quotes in regardless of OS
706 function wfEscapeShellArg( ) {
707 $args = func_get_args();
708 $first = true;
709 $retVal = '';
710 foreach ( $args as $arg ) {
711 if ( !$first ) {
712 $retVal .= ' ';
713 } else {
714 $first = false;
717 if ( wfIsWindows() ) {
718 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
719 } else {
720 $retVal .= escapeshellarg( $arg );
723 return $retVal;
727 * wfMerge attempts to merge differences between three texts.
728 * Returns true for a clean merge and false for failure or a conflict.
730 function wfMerge( $old, $mine, $yours, &$result ){
731 global $wgDiff3;
733 # This check may also protect against code injection in
734 # case of broken installations.
735 if(! file_exists( $wgDiff3 ) ){
736 return false;
739 # Make temporary files
740 $td = '/tmp/';
741 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
742 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
743 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
745 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
746 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
747 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
749 # Check for a conflict
750 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
751 wfEscapeShellArg( $mytextName ) . ' ' .
752 wfEscapeShellArg( $oldtextName ) . ' ' .
753 wfEscapeShellArg( $yourtextName );
754 $handle = popen( $cmd, 'r' );
756 if( fgets( $handle ) ){
757 $conflict = true;
758 } else {
759 $conflict = false;
761 pclose( $handle );
763 # Merge differences
764 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
765 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
766 $handle = popen( $cmd, 'r' );
767 $result = '';
768 do {
769 $data = fread( $handle, 8192 );
770 if ( strlen( $data ) == 0 ) {
771 break;
773 $result .= $data;
774 } while ( true );
775 pclose( $handle );
776 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
777 return ! $conflict;
781 * @todo document
783 function wfVarDump( $var ) {
784 global $wgOut;
785 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
786 if ( headers_sent() || !@is_object( $wgOut ) ) {
787 print $s;
788 } else {
789 $wgOut->addHTML( $s );
794 * Provide a simple HTTP error.
796 function wfHttpError( $code, $label, $desc ) {
797 global $wgOut;
798 $wgOut->disable();
799 header( "HTTP/1.0 $code $label" );
800 header( "Status: $code $label" );
801 $wgOut->sendCacheControl();
803 # Don't send content if it's a HEAD request.
804 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
805 header( 'Content-type: text/plain' );
806 print "$desc\n";
811 * Converts an Accept-* header into an array mapping string values to quality
812 * factors
814 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
815 # No arg means accept anything (per HTTP spec)
816 if( !$accept ) {
817 return array( $def => 1 );
820 $prefs = array();
822 $parts = explode( ',', $accept );
824 foreach( $parts as $part ) {
825 # FIXME: doesn't deal with params like 'text/html; level=1'
826 @list( $value, $qpart ) = explode( ';', $part );
827 if( !isset( $qpart ) ) {
828 $prefs[$value] = 1;
829 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
830 $prefs[$value] = $match[1];
834 return $prefs;
838 * @todo document
839 * @private
841 function mimeTypeMatch( $type, $avail ) {
842 if( array_key_exists($type, $avail) ) {
843 return $type;
844 } else {
845 $parts = explode( '/', $type );
846 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
847 return $parts[0] . '/*';
848 } elseif( array_key_exists( '*/*', $avail ) ) {
849 return '*/*';
850 } else {
851 return NULL;
857 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
858 * XXX: generalize to negotiate other stuff
860 function wfNegotiateType( $cprefs, $sprefs ) {
861 $combine = array();
863 foreach( array_keys($sprefs) as $type ) {
864 $parts = explode( '/', $type );
865 if( $parts[1] != '*' ) {
866 $ckey = mimeTypeMatch( $type, $cprefs );
867 if( $ckey ) {
868 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
873 foreach( array_keys( $cprefs ) as $type ) {
874 $parts = explode( '/', $type );
875 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
876 $skey = mimeTypeMatch( $type, $sprefs );
877 if( $skey ) {
878 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
883 $bestq = 0;
884 $besttype = NULL;
886 foreach( array_keys( $combine ) as $type ) {
887 if( $combine[$type] > $bestq ) {
888 $besttype = $type;
889 $bestq = $combine[$type];
893 return $besttype;
897 * Array lookup
898 * Returns an array where the values in the first array are replaced by the
899 * values in the second array with the corresponding keys
901 * @return array
903 function wfArrayLookup( $a, $b ) {
904 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
909 * Ideally we'd be using actual time fields in the db
910 * @todo fixme
912 function wfTimestamp2Unix( $ts ) {
913 return gmmktime( ( (int)substr( $ts, 8, 2) ),
914 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
915 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
916 (int)substr( $ts, 0, 4 ) );
920 * @todo document
922 function wfUnix2Timestamp( $unixtime ) {
923 return gmdate( 'YmdHis', $unixtime );
927 * @todo document
929 function wfTimestampNow() {
930 # return NOW
931 return gmdate( 'YmdHis' );
935 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
937 function wfInvertTimestamp( $ts ) {
938 return strtr(
939 $ts,
940 '0123456789',
941 '9876543210'
946 * Reference-counted warning suppression
948 function wfSuppressWarnings( $end = false ) {
949 static $suppressCount = 0;
950 static $originalLevel = false;
952 if ( $end ) {
953 if ( $suppressCount ) {
954 $suppressCount --;
955 if ( !$suppressCount ) {
956 error_reporting( $originalLevel );
959 } else {
960 if ( !$suppressCount ) {
961 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
963 $suppressCount++;
968 * Restore error level to previous value
970 function wfRestoreWarnings() {
971 wfSuppressWarnings( true );
974 # Autodetect, convert and provide timestamps of various types
976 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
977 define('TS_UNIX',0);
978 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
979 define('TS_MW',1);
980 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
981 define('TS_DB',2);
984 * @todo document
986 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
987 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
988 # TS_DB
989 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
990 (int)$da[2],(int)$da[3],(int)$da[1]);
991 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
992 # TS_MW
993 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
994 (int)$da[2],(int)$da[3],(int)$da[1]);
995 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
996 # TS_UNIX
997 $uts=$ts;
1000 if ($ts==0)
1001 $uts=time();
1002 switch($outputtype) {
1003 case TS_UNIX:
1004 return $uts;
1005 break;
1006 case TS_MW:
1007 return gmdate( 'YmdHis', $uts );
1008 break;
1009 case TS_DB:
1010 return gmdate( 'Y-m-d H:i:s', $uts );
1011 break;
1012 default:
1013 return;
1018 * Check where as the operating system is Windows
1020 * @todo document
1021 * @return bool True if it's windows, False otherwise.
1023 function wfIsWindows() {
1024 if (substr(php_uname(), 0, 7) == 'Windows') {
1025 return true;
1026 } else {
1027 return false;