Adjust UTF-8 generator for correctness. (Upper private use area, probably affects...
[mediawiki.git] / includes / GlobalFunctions.php
blob9d156dd023c93a3c56178403a970198d36725af9
1 <?php
2 # Global functions used everywhere
3 # $Id$
5 $wgNumberOfArticles = -1; # Unset
6 $wgTotalViews = -1;
7 $wgTotalEdits = -1;
9 require_once( 'DatabaseFunctions.php' );
10 require_once( 'UpdateClasses.php' );
11 require_once( 'LogPage.php' );
14 * Compatibility functions
17 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
18 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
19 # such as the new autoglobals.
21 if( !function_exists('iconv') ) {
22 # iconv support is not in the default configuration and so may not be present.
23 # Assume will only ever use utf-8 and iso-8859-1.
24 # This will *not* work in all circumstances.
25 function iconv( $from, $to, $string ) {
26 if(strcasecmp( $from, $to ) == 0) return $string;
27 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
28 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
29 return $string;
33 if( !function_exists('file_get_contents') ) {
34 # Exists in PHP 4.3.0+
35 function file_get_contents( $filename ) {
36 return implode( '', file( $filename ) );
40 if( !function_exists('is_a') ) {
41 # Exists in PHP 4.2.0+
42 function is_a( $object, $class_name ) {
43 return
44 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
45 is_subclass_of( $object, $class_name );
49 # UTF-8 substr function based on a PHP manual comment
50 if ( !function_exists( 'mb_substr' ) ) {
51 function mb_substr($str,$start)
53 preg_match_all("/./us", $str, $ar);
55 if(func_num_args() >= 3) {
56 $end = func_get_arg(2);
57 return join("",array_slice($ar[0],$start,$end));
58 } else {
59 return join("",array_slice($ar[0],$start));
64 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
65 # with no UTF-8 support.
66 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT, $charset='ISO-8859-1' ) {
67 static $trans;
68 if( !isset( $trans ) ) {
69 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
70 # Assumes $charset will always be the same through a run, and only understands
71 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
72 # ones will result in a bad link.
73 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
74 $trans = array_map( 'utf8_encode', $trans );
77 return strtr( $string, $trans );
80 $wgRandomSeeded = false;
82 # Seed Mersenne Twister
83 # Only necessary in PHP < 4.2.0
84 function wfSeedRandom()
86 global $wgRandomSeeded;
88 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
89 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
90 mt_srand( $seed );
91 $wgRandomSeeded = true;
95 # Generates a URL from a URL-encoded title and a query string
96 # Title::getLocalURL() is preferred in most cases
98 function wfLocalUrl( $a, $q = '' )
100 global $wgServer, $wgScript, $wgArticlePath;
102 $a = str_replace( ' ', '_', $a );
104 if ( '' == $a ) {
105 if( '' == $q ) {
106 $a = $wgScript;
107 } else {
108 $a = $wgScript.'?'.$q;
110 } else if ( '' == $q ) {
111 $a = str_replace( '$1', $a, $wgArticlePath );
112 } else if ($wgScript != '' ) {
113 $a = "{$wgScript}?title={$a}&{$q}";
114 } else { //XXX hackish solution for toplevel wikis
115 $a = "/{$a}?{$q}";
117 return $a;
120 function wfLocalUrlE( $a, $q = '' )
122 return htmlspecialchars( wfLocalUrl( $a, $q ) );
123 # die( "Call to obsolete function wfLocalUrlE()" );
126 # We want / and : to be included as literal characters in our title URLs.
127 # %2F in the page titles seems to fatally break for some reason.
129 function wfUrlencode ( $s )
131 $s = urlencode( $s );
132 $s = preg_replace( '/%3[Aa]/', ':', $s );
133 $s = preg_replace( '/%2[Ff]/', '/', $s );
135 return $s;
138 # Return the UTF-8 sequence for a given Unicode code point.
139 # Currently doesn't work for values outside the Basic Multilingual Plane.
141 function wfUtf8Sequence( $codepoint ) {
142 if($codepoint < 0x80) return chr($codepoint);
143 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
144 chr($codepoint & 0x3f | 0x80);
145 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
146 chr($codepoint >> 6 & 0x3f | 0x80) .
147 chr($codepoint & 0x3f | 0x80);
148 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 | 0xf0) .
149 chr($codepoint >> 12 & 0x3f | 0x80) .
150 chr($codepoint >> 6 & 0x3f | 0x80) .
151 chr($codepoint & 0x3f | 0x80);
153 # There should be no assigned code points outside this range, but...
154 return "&#$codepoint;";
157 # Converts numeric character entities to UTF-8
158 function wfMungeToUtf8( $string ) {
159 global $wgInputEncoding; # This is debatable
160 #$string = iconv($wgInputEncoding, "UTF-8", $string);
161 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
162 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
163 # Should also do named entities here
164 return $string;
167 # Converts a single UTF-8 character into the corresponding HTML character entity
168 # (for use with preg_replace_callback)
169 function wfUtf8Entity( $matches ) {
170 $char = $matches[0];
171 # Find the length
172 $z = ord( $char{0} );
173 if ( $z & 0x80 ) {
174 $length = 0;
175 while ( $z & 0x80 ) {
176 $length++;
177 $z <<= 1;
179 } else {
180 $length = 1;
183 if ( $length != strlen( $char ) ) {
184 return '';
186 if ( $length == 1 ) {
187 return $char;
190 # Mask off the length-determining bits and shift back to the original location
191 $z &= 0xff;
192 $z >>= $length;
194 # Add in the free bits from subsequent bytes
195 for ( $i=1; $i<$length; $i++ ) {
196 $z <<= 6;
197 $z |= ord( $char{$i} ) & 0x3f;
200 # Make entity
201 return "&#$z;";
204 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
205 function wfUtf8ToHTML($string) {
206 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
209 function wfDebug( $text, $logonly = false )
211 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
213 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
214 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
215 return;
218 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
219 $wgOut->debug( $text );
221 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
222 error_log( $text, 3, $wgDebugLogFile );
226 # Log for database errors
227 function wfLogDBError( $text ) {
228 global $wgDBerrorLog;
229 if ( $wgDBerrorLog ) {
230 $text = date('D M j G:i:s T Y') . "\t".$text;
231 error_log( $text, 3, $wgDBerrorLog );
235 function logProfilingData()
237 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
238 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
239 $now = wfTime();
241 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
242 $start = (float)$sec + (float)$usec;
243 $elapsed = $now - $start;
244 if ( $wgProfiling ) {
245 $prof = wfGetProfilingOutput( $start, $elapsed );
246 $forward = '';
247 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
248 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
249 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
250 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
251 if( !empty( $_SERVER['HTTP_FROM'] ) )
252 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
253 if( $forward )
254 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
255 if($wgUser->getId() == 0)
256 $forward .= ' anon';
257 $log = sprintf( "%s\t%04.3f\t%s\n",
258 gmdate( 'YmdHis' ), $elapsed,
259 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
260 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
261 error_log( $log . $prof, 3, $wgDebugLogFile );
266 # Check if the wiki read-only lock file is present. This can be used to lock off
267 # editing functions, but doesn't guarantee that the database will not be modified.
268 function wfReadOnly() {
269 global $wgReadOnlyFile;
271 if ( '' == $wgReadOnlyFile ) {
272 return false;
274 return is_file( $wgReadOnlyFile );
277 $wgReplacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
279 # Get a message from anywhere
280 function wfMsg( $key ) {
281 global $wgRequest;
282 if ( $wgRequest->getVal( 'debugmsg' ) ) {
283 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
284 return "/^()(.*)$/sD";
285 else
286 return $key;
288 $args = func_get_args();
289 if ( count( $args ) ) {
290 array_shift( $args );
292 return wfMsgReal( $key, $args, true );
295 # Get a message from the language file
296 function wfMsgNoDB( $key ) {
297 $args = func_get_args();
298 if ( count( $args ) ) {
299 array_shift( $args );
301 return wfMsgReal( $key, $args, false );
304 # Really get a message
305 function wfMsgReal( $key, $args, $useDB ) {
306 global $wgReplacementKeys, $wgMessageCache, $wgLang;
308 $fname = 'wfMsg';
309 wfProfileIn( $fname );
310 if ( $wgMessageCache ) {
311 $message = $wgMessageCache->get( $key, $useDB );
312 } elseif ( $wgLang ) {
313 $message = $wgLang->getMessage( $key );
314 } else {
315 wfDebug( "No language object when getting $key\n" );
316 $message = "&lt;$key&gt;";
319 # Replace arguments
320 if( count( $args ) ) {
321 $message = str_replace( $wgReplacementKeys, $args, $message );
323 wfProfileOut( $fname );
324 return $message;
327 # Just like exit() but makes a note of it.
328 # Commits open transactions except if the error parameter is set
329 function wfAbruptExit( $error = false ){
330 global $wgLoadBalancer;
331 static $called = false;
332 if ( $called ){
333 exit();
335 $called = true;
337 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
338 $bt = debug_backtrace();
339 for($i = 0; $i < count($bt) ; $i++){
340 $file = $bt[$i]['file'];
341 $line = $bt[$i]['line'];
342 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
344 } else {
345 wfDebug('WARNING: Abrupt exit\n');
347 if ( !$error ) {
348 $wgLoadBalancer->closeAll();
350 exit();
353 function wfErrorExit() {
354 wfAbruptExit( true );
357 # This is meant as a debugging aid to track down where bad data comes from.
358 # Shouldn't be used in production code except maybe in "shouldn't happen" areas.
360 function wfDebugDieBacktrace( $msg = '' ) {
361 global $wgCommandLineMode;
363 if ( function_exists( 'debug_backtrace' ) ) {
364 if ( $wgCommandLineMode ) {
365 $msg .= "\nBacktrace:\n";
366 } else {
367 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
369 $backtrace = debug_backtrace();
370 foreach( $backtrace as $call ) {
371 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
372 $file = $f[count($f)-1];
373 if ( $wgCommandLineMode ) {
374 $msg .= "$file line {$call['line']} calls ";
375 } else {
376 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
378 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
379 $msg .= $call['function'] . '()';
381 if ( $wgCommandLineMode ) {
382 $msg .= "\n";
383 } else {
384 $msg .= "</li>\n";
388 die( $msg );
392 /* Some generic result counters, pulled out of SearchEngine */
394 function wfShowingResults( $offset, $limit )
396 global $wgLang;
397 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
400 function wfShowingResultsNum( $offset, $limit, $num )
402 global $wgLang;
403 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
406 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
408 global $wgUser, $wgLang;
409 $fmtLimit = $wgLang->formatNum( $limit );
410 $prev = wfMsg( 'prevn', $fmtLimit );
411 $next = wfMsg( 'nextn', $fmtLimit );
412 $link = wfUrlencode( $link );
414 $sk = $wgUser->getSkin();
415 if ( 0 != $offset ) {
416 $po = $offset - $limit;
417 if ( $po < 0 ) { $po = 0; }
418 $q = "limit={$limit}&offset={$po}";
419 if ( '' != $query ) { $q .= '&'.$query; }
420 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
421 } else { $plink = $prev; }
423 $no = $offset + $limit;
424 $q = 'limit='.$limit.'&offset='.$no;
425 if ( '' != $query ) { $q .= '&'.$query; }
427 if ( $atend ) {
428 $nlink = $next;
429 } else {
430 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
432 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
433 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
434 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
435 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
436 wfNumLink( $offset, 500, $link, $query );
438 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
441 function wfNumLink( $offset, $limit, $link, $query = '' )
443 global $wgUser, $wgLang;
444 if ( '' == $query ) { $q = ''; }
445 else { $q = $query.'&'; }
446 $q .= 'limit='.$limit.'&offset='.$offset;
448 $fmtLimit = $wgLang->formatNum( $limit );
449 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
450 return $s;
453 function wfClientAcceptsGzip() {
454 global $wgUseGzip;
455 if( $wgUseGzip ) {
456 # FIXME: we may want to blacklist some broken browsers
457 if( preg_match(
458 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
459 $_SERVER['HTTP_ACCEPT_ENCODING'],
460 $m ) ) {
461 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
462 wfDebug( " accepts gzip\n" );
463 return true;
466 return false;
469 # Yay, more global functions!
470 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
471 global $wgRequest;
472 return $wgRequest->getLimitOffset( $deflimit, $optionname );
475 # Escapes the given text so that it may be output using addWikiText()
476 # without any linking, formatting, etc. making its way through. This
477 # is achieved by substituting certain characters with HTML entities.
478 # As required by the callers, <nowiki> is not used. It currently does
479 # not filter out characters which have special meaning only at the
480 # start of a line, such as "*".
481 function wfEscapeWikiText( $text )
483 $text = str_replace(
484 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
485 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
486 htmlspecialchars($text) );
487 return $text;
490 function wfQuotedPrintable( $string, $charset = '' )
492 # Probably incomplete; see RFC 2045
493 if( empty( $charset ) ) {
494 global $wgInputEncoding;
495 $charset = $wgInputEncoding;
497 $charset = strtoupper( $charset );
498 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
500 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
501 $replace = $illegal . '\t ?_';
502 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
503 $out = "=?$charset?Q?";
504 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
505 $out .= '?=';
506 return $out;
509 function wfTime(){
510 $st = explode( ' ', microtime() );
511 return (float)$st[0] + (float)$st[1];
514 # Changes the first character to an HTML entity
515 function wfHtmlEscapeFirst( $text ) {
516 $ord = ord($text);
517 $newText = substr($text, 1);
518 return "&#$ord;$newText";
521 # Sets dest to source and returns the original value of dest
522 # If source is NULL, it just returns the value, it doesn't set the variable
523 function wfSetVar( &$dest, $source )
525 $temp = $dest;
526 if ( !is_null( $source ) ) {
527 $dest = $source;
529 return $temp;
532 # As for wfSetVar except setting a bit
533 function wfSetBit( &$dest, $bit, $state = true ) {
534 $temp = (bool)($dest & $bit );
535 if ( !is_null( $state ) ) {
536 if ( $state ) {
537 $dest |= $bit;
538 } else {
539 $dest &= ~$bit;
542 return $temp;
545 # This function takes two arrays as input, and returns a CGI-style string, e.g.
546 # "days=7&limit=100". Options in the first array override options in the second.
547 # Options set to "" will not be output.
548 function wfArrayToCGI( $array1, $array2 = NULL )
550 if ( !is_null( $array2 ) ) {
551 $array1 = $array1 + $array2;
554 $cgi = '';
555 foreach ( $array1 as $key => $value ) {
556 if ( '' !== $value ) {
557 if ( '' != $cgi ) {
558 $cgi .= '&';
560 $cgi .= $key.'='.$value;
563 return $cgi;
566 # This is obsolete, use SquidUpdate::purge()
567 function wfPurgeSquidServers ($urlArr) {
568 SquidUpdate::purge( $urlArr );
571 # Windows-compatible version of escapeshellarg()
572 # Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
573 # function puts single quotes in regardless of OS
574 function wfEscapeShellArg( )
576 $args = func_get_args();
577 $first = true;
578 $retVal = '';
579 foreach ( $args as $arg ) {
580 if ( !$first ) {
581 $retVal .= ' ';
582 } else {
583 $first = false;
586 if ( wfIsWindows() ) {
587 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
588 } else {
589 $retVal .= escapeshellarg( $arg );
592 return $retVal;
595 # wfMerge attempts to merge differences between three texts.
596 # Returns true for a clean merge and false for failure or a conflict.
598 function wfMerge( $old, $mine, $yours, &$result ){
599 global $wgDiff3;
601 # This check may also protect against code injection in
602 # case of broken installations.
603 if(! file_exists( $wgDiff3 ) ){
604 return false;
607 # Make temporary files
608 $td = '/tmp/';
609 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
610 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
611 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
613 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
614 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
615 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
617 # Check for a conflict
618 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
619 wfEscapeShellArg( $mytextName ) . ' ' .
620 wfEscapeShellArg( $oldtextName ) . ' ' .
621 wfEscapeShellArg( $yourtextName );
622 $handle = popen( $cmd, 'r' );
624 if( fgets( $handle ) ){
625 $conflict = true;
626 } else {
627 $conflict = false;
629 pclose( $handle );
631 # Merge differences
632 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
633 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
634 $handle = popen( $cmd, 'r' );
635 $result = '';
636 do {
637 $data = fread( $handle, 8192 );
638 if ( strlen( $data ) == 0 ) {
639 break;
641 $result .= $data;
642 } while ( true );
643 pclose( $handle );
644 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
645 return ! $conflict;
648 function wfVarDump( $var )
650 global $wgOut;
651 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
652 if ( headers_sent() || !@is_object( $wgOut ) ) {
653 print $s;
654 } else {
655 $wgOut->addHTML( $s );
659 # Provide a simple HTTP error.
660 function wfHttpError( $code, $label, $desc ) {
661 global $wgOut;
662 $wgOut->disable();
663 header( "HTTP/1.0 $code $label" );
664 header( "Status: $code $label" );
665 $wgOut->sendCacheControl();
667 # Don't send content if it's a HEAD request.
668 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
669 header( 'Content-type: text/plain' );
670 print "$desc\n";
674 # Converts an Accept-* header into an array mapping string values to quality factors
675 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
676 # No arg means accept anything (per HTTP spec)
677 if( !$accept ) {
678 return array( $def => 1 );
681 $prefs = array();
683 $parts = explode( ',', $accept );
685 foreach( $parts as $part ) {
686 # FIXME: doesn't deal with params like 'text/html; level=1'
687 @list( $value, $qpart ) = explode( ';', $part );
688 if( !isset( $qpart ) ) {
689 $prefs[$value] = 1;
690 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
691 $prefs[$value] = $match[1];
695 return $prefs;
698 /* private */ function mimeTypeMatch( $type, $avail ) {
699 if( array_key_exists($type, $avail) ) {
700 return $type;
701 } else {
702 $parts = explode( '/', $type );
703 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
704 return $parts[0] . '/*';
705 } elseif( array_key_exists( '*/*', $avail ) ) {
706 return '*/*';
707 } else {
708 return NULL;
713 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
714 # XXX: generalize to negotiate other stuff
715 function wfNegotiateType( $cprefs, $sprefs ) {
716 $combine = array();
718 foreach( array_keys($sprefs) as $type ) {
719 $parts = explode( '/', $type );
720 if( $parts[1] != '*' ) {
721 $ckey = mimeTypeMatch( $type, $cprefs );
722 if( $ckey ) {
723 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
728 foreach( array_keys( $cprefs ) as $type ) {
729 $parts = explode( '/', $type );
730 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
731 $skey = mimeTypeMatch( $type, $sprefs );
732 if( $skey ) {
733 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
738 $bestq = 0;
739 $besttype = NULL;
741 foreach( array_keys( $combine ) as $type ) {
742 if( $combine[$type] > $bestq ) {
743 $besttype = $type;
744 $bestq = $combine[$type];
748 return $besttype;
751 # Array lookup
752 # Returns an array where the values in the first array are replaced by the
753 # values in the second array with the corresponding keys
754 function wfArrayLookup( $a, $b )
756 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
760 # Ideally we'd be using actual time fields in the db
761 function wfTimestamp2Unix( $ts ) {
762 return gmmktime( ( (int)substr( $ts, 8, 2) ),
763 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
764 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
765 (int)substr( $ts, 0, 4 ) );
768 function wfUnix2Timestamp( $unixtime ) {
769 return gmdate( 'YmdHis', $unixtime );
772 function wfTimestampNow() {
773 # return NOW
774 return gmdate( 'YmdHis' );
777 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
778 function wfInvertTimestamp( $ts ) {
779 return strtr(
780 $ts,
781 '0123456789',
782 '9876543210'
786 # Reference-counted warning suppression
787 function wfSuppressWarnings( $end = false ) {
788 static $suppressCount = 0;
789 static $originalLevel = false;
791 if ( $end ) {
792 if ( $suppressCount ) {
793 $suppressCount --;
794 if ( !$suppressCount ) {
795 error_reporting( $originalLevel );
798 } else {
799 if ( !$suppressCount ) {
800 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
802 $suppressCount++;
806 # Restore error level to previous value
807 function wfRestoreWarnings() {
808 wfSuppressWarnings( true );
811 # Autodetect, convert and provide timestamps of various types
812 define('TS_UNIX',0); # Standard unix timestamp (number of seconds since 1 Jan 1970)
813 define('TS_MW',1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
814 define('TS_DB',2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
816 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
817 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
818 # TS_DB
819 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
820 (int)$da[2],(int)$da[3],(int)$da[1]);
821 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
822 # TS_MW
823 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
824 (int)$da[2],(int)$da[3],(int)$da[1]);
825 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
826 # TS_UNIX
827 $uts=$ts;
830 if ($ts==0)
831 $uts=time();
832 switch($outputtype) {
833 case TS_UNIX:
834 return $uts;
835 break;
836 case TS_MW:
837 return gmdate( 'YmdHis', $uts );
838 break;
839 case TS_DB:
840 return gmdate( 'Y-m-d H:i:s', $uts );
841 break;
842 default:
843 return;
847 function wfIsWindows() {
848 if (substr(php_uname(), 0, 7) == 'Windows') {
849 return true;
850 } else {
851 return false;