massive double to single quotes conversion. I have not noticed any bug after a lot...
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 # Global functions used everywhere
3 # $Id$
4
5 $wgNumberOfArticles = -1; # Unset
6 $wgTotalViews = -1;
7 $wgTotalEdits = -1;
8
9 require_once( 'DatabaseFunctions.php' );
10 require_once( 'UpdateClasses.php' );
11 require_once( 'LogPage.php' );
12
13 /*
14 * Compatibility functions
15 */
16
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.
20
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;
30 }
31 }
32
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 ) );
37 }
38 }
39
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 );
46 }
47 }
48
49 # html_entity_decode exists in PHP 4.3.0+ but is FATALLY BROKEN even then,
50 # with no UTF-8 support.
51 function do_html_entity_decode( $string, $quote_style=ENT_COMPAT, $charset='ISO-8859-1' ) {
52 static $trans;
53 if( !isset( $trans ) ) {
54 $trans = array_flip( get_html_translation_table( HTML_ENTITIES, $quote_style ) );
55 # Assumes $charset will always be the same through a run, and only understands
56 # utf-8 or default. Note - mixing latin1 named entities and unicode numbered
57 # ones will result in a bad link.
58 if( strcasecmp( 'utf-8', $charset ) == 0 ) {
59 $trans = array_map( 'utf8_encode', $trans );
60 }
61 }
62 return strtr( $string, $trans );
63 }
64
65 $wgRandomSeeded = false;
66
67 # Seed Mersenne Twister
68 # Only necessary in PHP < 4.2.0
69 function wfSeedRandom()
70 {
71 global $wgRandomSeeded;
72
73 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
74 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
75 mt_srand( $seed );
76 $wgRandomSeeded = true;
77 }
78 }
79
80 # Generates a URL from a URL-encoded title and a query string
81 # Title::getLocalURL() is preferred in most cases
82 #
83 function wfLocalUrl( $a, $q = '' )
84 {
85 global $wgServer, $wgScript, $wgArticlePath;
86
87 $a = str_replace( ' ', '_', $a );
88
89 if ( '' == $a ) {
90 if( '' == $q ) {
91 $a = $wgScript;
92 } else {
93 $a = $wgScript.'?'.$q;
94 }
95 } else if ( '' == $q ) {
96 $a = str_replace( '$1', $a, $wgArticlePath );
97 } else if ($wgScript != '' ) {
98 $a = "{$wgScript}?title={$a}&{$q}";
99 } else { //XXX hackish solution for toplevel wikis
100 $a = "/{$a}?{$q}";
101 }
102 return $a;
103 }
104
105 function wfLocalUrlE( $a, $q = '' )
106 {
107 return htmlspecialchars( wfLocalUrl( $a, $q ) );
108 # die( "Call to obsolete function wfLocalUrlE()" );
109 }
110
111 # We want / and : to be included as literal characters in our title URLs.
112 # %2F in the page titles seems to fatally break for some reason.
113 #
114 function wfUrlencode ( $s )
115 {
116 $s = urlencode( $s );
117 $s = preg_replace( '/%3[Aa]/', ':', $s );
118 $s = preg_replace( '/%2[Ff]/', '/', $s );
119
120 return $s;
121 }
122
123 # Return the UTF-8 sequence for a given Unicode code point.
124 # Currently doesn't work for values outside the Basic Multilingual Plane.
125 #
126 function wfUtf8Sequence( $codepoint ) {
127 if($codepoint < 0x80) return chr($codepoint);
128 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
129 chr($codepoint & 0x3f | 0x80);
130 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
131 chr($codepoint >> 6 & 0x3f | 0x80) .
132 chr($codepoint & 0x3f | 0x80);
133 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
134 chr($codepoint >> 12 & 0x3f | 0x80) .
135 chr($codepoint >> 6 & 0x3f | 0x80) .
136 chr($codepoint & 0x3f | 0x80);
137 # Doesn't yet handle outside the BMP
138 return "&#$codepoint;";
139 }
140
141 # Converts numeric character entities to UTF-8
142 function wfMungeToUtf8( $string ) {
143 global $wgInputEncoding; # This is debatable
144 #$string = iconv($wgInputEncoding, "UTF-8", $string);
145 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
146 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
147 # Should also do named entities here
148 return $string;
149 }
150
151 # Converts a single UTF-8 character into the corresponding HTML character entity
152 # (for use with preg_replace_callback)
153 function wfUtf8Entity( $matches ) {
154 $char = $matches[0];
155 # Find the length
156 $z = ord( $char{0} );
157 if ( $z & 0x80 ) {
158 $length = 0;
159 while ( $z & 0x80 ) {
160 $length++;
161 $z <<= 1;
162 }
163 } else {
164 $length = 1;
165 }
166
167 if ( $length != strlen( $char ) ) {
168 return '';
169 }
170 if ( $length == 1 ) {
171 return $char;
172 }
173
174 # Mask off the length-determining bits and shift back to the original location
175 $z &= 0xff;
176 $z >>= $length;
177
178 # Add in the free bits from subsequent bytes
179 for ( $i=1; $i<$length; $i++ ) {
180 $z <<= 6;
181 $z |= ord( $char{$i} ) & 0x3f;
182 }
183
184 # Make entity
185 return "&#$z;";
186 }
187
188 # Converts all multi-byte characters in a UTF-8 string into the appropriate character entity
189 function wfUtf8ToHTML($string) {
190 return preg_replace_callback( '/[\\xc0-\\xfd][\\x80-\\xbf]*/', 'wfUtf8Entity', $string );
191 }
192
193 function wfDebug( $text, $logonly = false )
194 {
195 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
196
197 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
198 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
199 return;
200 }
201
202 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
203 $wgOut->debug( $text );
204 }
205 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
206 error_log( $text, 3, $wgDebugLogFile );
207 }
208 }
209
210 # Log for database errors
211 function wfLogDBError( $text ) {
212 global $wgDBerrorLog;
213 if ( $wgDBerrorLog ) {
214 $text = date('D M j G:i:s T Y') . "\t".$text;
215 error_log( $text, 3, $wgDBerrorLog );
216 }
217 }
218
219 function logProfilingData()
220 {
221 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
222 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
223 $now = wfTime();
224
225 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
226 $start = (float)$sec + (float)$usec;
227 $elapsed = $now - $start;
228 if ( $wgProfiling ) {
229 $prof = wfGetProfilingOutput( $start, $elapsed );
230 $forward = '';
231 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
232 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
233 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
234 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
235 if( !empty( $_SERVER['HTTP_FROM'] ) )
236 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
237 if( $forward )
238 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
239 if($wgUser->getId() == 0)
240 $forward .= ' anon';
241 $log = sprintf( "%s\t%04.3f\t%s\n",
242 gmdate( 'YmdHis' ), $elapsed,
243 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
244 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
245 error_log( $log . $prof, 3, $wgDebugLogFile );
246 }
247 }
248 }
249
250 # Check if the wiki read-only lock file is present. This can be used to lock off
251 # editing functions, but doesn't guarantee that the database will not be modified.
252 function wfReadOnly() {
253 global $wgReadOnlyFile;
254
255 if ( '' == $wgReadOnlyFile ) {
256 return false;
257 }
258 return is_file( $wgReadOnlyFile );
259 }
260
261 $wgReplacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
262
263 # Get a message from anywhere
264 function wfMsg( $key ) {
265 global $wgRequest;
266 if ( $wgRequest->getVal( 'debugmsg' ) ) {
267 if ( $key == 'linktrail' /* a special case where we want to return something specific */ )
268 return "/^()(.*)$/sD";
269 else
270 return $key;
271 }
272 $args = func_get_args();
273 if ( count( $args ) ) {
274 array_shift( $args );
275 }
276 return wfMsgReal( $key, $args, true );
277 }
278
279 # Get a message from the language file
280 function wfMsgNoDB( $key ) {
281 $args = func_get_args();
282 if ( count( $args ) ) {
283 array_shift( $args );
284 }
285 return wfMsgReal( $key, $args, false );
286 }
287
288 # Really get a message
289 function wfMsgReal( $key, $args, $useDB ) {
290 global $wgReplacementKeys, $wgMessageCache, $wgLang;
291
292 $fname = 'wfMsg';
293 wfProfileIn( $fname );
294 if ( $wgMessageCache ) {
295 $message = $wgMessageCache->get( $key, $useDB );
296 } elseif ( $wgLang ) {
297 $message = $wgLang->getMessage( $key );
298 } else {
299 wfDebug( "No language object when getting $key\n" );
300 $message = "&lt;$key&gt;";
301 }
302
303 # Replace arguments
304 if( count( $args ) ) {
305 $message = str_replace( $wgReplacementKeys, $args, $message );
306 }
307 wfProfileOut( $fname );
308 return $message;
309 }
310
311 # Just like exit() but makes a note of it.
312 # Commits open transactions except if the error parameter is set
313 function wfAbruptExit( $error = false ){
314 global $wgLoadBalancer;
315 static $called = false;
316 if ( $called ){
317 exit();
318 }
319 $called = true;
320
321 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
322 $bt = debug_backtrace();
323 for($i = 0; $i < count($bt) ; $i++){
324 $file = $bt[$i]['file'];
325 $line = $bt[$i]['line'];
326 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
327 }
328 } else {
329 wfDebug('WARNING: Abrupt exit\n');
330 }
331 if ( !$error ) {
332 $wgLoadBalancer->closeAll();
333 }
334 exit();
335 }
336
337 function wfErrorExit() {
338 wfAbruptExit( true );
339 }
340
341 # This is meant as a debugging aid to track down where bad data comes from.
342 # Shouldn't be used in production code except maybe in "shouldn't happen" areas.
343 #
344 function wfDebugDieBacktrace( $msg = '' ) {
345 global $wgCommandLineMode;
346
347 if ( function_exists( 'debug_backtrace' ) ) {
348 if ( $wgCommandLineMode ) {
349 $msg .= "\nBacktrace:\n";
350 } else {
351 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
352 }
353 $backtrace = debug_backtrace();
354 foreach( $backtrace as $call ) {
355 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
356 $file = $f[count($f)-1];
357 if ( $wgCommandLineMode ) {
358 $msg .= "$file line {$call['line']} calls ";
359 } else {
360 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
361 }
362 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
363 $msg .= $call['function'] . '()';
364
365 if ( $wgCommandLineMode ) {
366 $msg .= "\n";
367 } else {
368 $msg .= "</li>\n";
369 }
370 }
371 }
372 die( $msg );
373 }
374
375
376 /* Some generic result counters, pulled out of SearchEngine */
377
378 function wfShowingResults( $offset, $limit )
379 {
380 global $wgLang;
381 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
382 }
383
384 function wfShowingResultsNum( $offset, $limit, $num )
385 {
386 global $wgLang;
387 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
388 }
389
390 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false )
391 {
392 global $wgUser, $wgLang;
393 $fmtLimit = $wgLang->formatNum( $limit );
394 $prev = wfMsg( 'prevn', $fmtLimit );
395 $next = wfMsg( 'nextn', $fmtLimit );
396 $link = wfUrlencode( $link );
397
398 $sk = $wgUser->getSkin();
399 if ( 0 != $offset ) {
400 $po = $offset - $limit;
401 if ( $po < 0 ) { $po = 0; }
402 $q = "limit={$limit}&offset={$po}";
403 if ( '' != $query ) { $q .= '&'.$query; }
404 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
405 } else { $plink = $prev; }
406
407 $no = $offset + $limit;
408 $q = 'limit='.$limit.'&offset='.$no;
409 if ( '' != $query ) { $q .= '&'.$query; }
410
411 if ( $atend ) {
412 $nlink = $next;
413 } else {
414 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
415 }
416 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
417 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
418 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
419 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
420 wfNumLink( $offset, 500, $link, $query );
421
422 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
423 }
424
425 function wfNumLink( $offset, $limit, $link, $query = '' )
426 {
427 global $wgUser, $wgLang;
428 if ( '' == $query ) { $q = ''; }
429 else { $q = $query.'&'; }
430 $q .= 'limit='.$limit.'&offset='.$offset;
431
432 $fmtLimit = $wgLang->formatNum( $limit );
433 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
434 return $s;
435 }
436
437 function wfClientAcceptsGzip() {
438 global $wgUseGzip;
439 if( $wgUseGzip ) {
440 # FIXME: we may want to blacklist some broken browsers
441 if( preg_match(
442 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
443 $_SERVER['HTTP_ACCEPT_ENCODING'],
444 $m ) ) {
445 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
446 wfDebug( " accepts gzip\n" );
447 return true;
448 }
449 }
450 return false;
451 }
452
453 # Yay, more global functions!
454 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
455 global $wgUser, $wgRequest;
456
457 $limit = $wgRequest->getInt( 'limit', 0 );
458 if( $limit < 0 ) $limit = 0;
459 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
460 $limit = (int)$wgUser->getOption( $optionname );
461 }
462 if( $limit <= 0 ) $limit = $deflimit;
463 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
464
465 $offset = $wgRequest->getInt( 'offset', 0 );
466 if( $offset < 0 ) $offset = 0;
467
468 return array( $limit, $offset );
469 }
470
471 # Escapes the given text so that it may be output using addWikiText()
472 # without any linking, formatting, etc. making its way through. This
473 # is achieved by substituting certain characters with HTML entities.
474 # As required by the callers, <nowiki> is not used. It currently does
475 # not filter out characters which have special meaning only at the
476 # start of a line, such as "*".
477 function wfEscapeWikiText( $text )
478 {
479 $text = str_replace(
480 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
481 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
482 htmlspecialchars($text) );
483 return $text;
484 }
485
486 function wfQuotedPrintable( $string, $charset = '' )
487 {
488 # Probably incomplete; see RFC 2045
489 if( empty( $charset ) ) {
490 global $wgInputEncoding;
491 $charset = $wgInputEncoding;
492 }
493 $charset = strtoupper( $charset );
494 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
495
496 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
497 $replace = $illegal . '\t ?_';
498 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
499 $out = "=?$charset?Q?";
500 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
501 $out .= '?=';
502 return $out;
503 }
504
505 function wfTime(){
506 $st = explode( ' ', microtime() );
507 return (float)$st[0] + (float)$st[1];
508 }
509
510 # Changes the first character to an HTML entity
511 function wfHtmlEscapeFirst( $text ) {
512 $ord = ord($text);
513 $newText = substr($text, 1);
514 return "&#$ord;$newText";
515 }
516
517 # Sets dest to source and returns the original value of dest
518 # If source is NULL, it just returns the value, it doesn't set the variable
519 function wfSetVar( &$dest, $source )
520 {
521 $temp = $dest;
522 if ( !is_null( $source ) ) {
523 $dest = $source;
524 }
525 return $temp;
526 }
527
528 # As for wfSetVar except setting a bit
529 function wfSetBit( &$dest, $bit, $state = true ) {
530 $temp = (bool)($dest & $bit );
531 if ( !is_null( $state ) ) {
532 if ( $state ) {
533 $dest |= $bit;
534 } else {
535 $dest &= ~$bit;
536 }
537 }
538 return $temp;
539 }
540
541 # This function takes two arrays as input, and returns a CGI-style string, e.g.
542 # "days=7&limit=100". Options in the first array override options in the second.
543 # Options set to "" will not be output.
544 function wfArrayToCGI( $array1, $array2 = NULL )
545 {
546 if ( !is_null( $array2 ) ) {
547 $array1 = $array1 + $array2;
548 }
549
550 $cgi = '';
551 foreach ( $array1 as $key => $value ) {
552 if ( '' !== $value ) {
553 if ( '' != $cgi ) {
554 $cgi .= '&';
555 }
556 $cgi .= $key.'='.$value;
557 }
558 }
559 return $cgi;
560 }
561
562 # This is obsolete, use SquidUpdate::purge()
563 function wfPurgeSquidServers ($urlArr) {
564 SquidUpdate::purge( $urlArr );
565 }
566
567 # Windows-compatible version of escapeshellarg()
568 # Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
569 # function puts single quotes in regardless of OS
570 function wfEscapeShellArg( )
571 {
572 $args = func_get_args();
573 $first = true;
574 $retVal = '';
575 foreach ( $args as $arg ) {
576 if ( !$first ) {
577 $retVal .= ' ';
578 } else {
579 $first = false;
580 }
581
582 if ( wfIsWindows() ) {
583 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
584 } else {
585 $retVal .= escapeshellarg( $arg );
586 }
587 }
588 return $retVal;
589 }
590
591 # wfMerge attempts to merge differences between three texts.
592 # Returns true for a clean merge and false for failure or a conflict.
593
594 function wfMerge( $old, $mine, $yours, &$result ){
595 global $wgDiff3;
596
597 # This check may also protect against code injection in
598 # case of broken installations.
599 if(! file_exists( $wgDiff3 ) ){
600 return false;
601 }
602
603 # Make temporary files
604 $td = '/tmp/';
605 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
606 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
607 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
608
609 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
610 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
611 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
612
613 # Check for a conflict
614 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
615 wfEscapeShellArg( $mytextName ) . ' ' .
616 wfEscapeShellArg( $oldtextName ) . ' ' .
617 wfEscapeShellArg( $yourtextName );
618 $handle = popen( $cmd, 'r' );
619
620 if( fgets( $handle ) ){
621 $conflict = true;
622 } else {
623 $conflict = false;
624 }
625 pclose( $handle );
626
627 # Merge differences
628 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
629 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
630 $handle = popen( $cmd, 'r' );
631 $result = '';
632 do {
633 $data = fread( $handle, 8192 );
634 if ( strlen( $data ) == 0 ) {
635 break;
636 }
637 $result .= $data;
638 } while ( true );
639 pclose( $handle );
640 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
641 return ! $conflict;
642 }
643
644 function wfVarDump( $var )
645 {
646 global $wgOut;
647 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
648 if ( headers_sent() || !@is_object( $wgOut ) ) {
649 print $s;
650 } else {
651 $wgOut->addHTML( $s );
652 }
653 }
654
655 # Provide a simple HTTP error.
656 function wfHttpError( $code, $label, $desc ) {
657 global $wgOut;
658 $wgOut->disable();
659 header( "HTTP/1.0 $code $label" );
660 header( "Status: $code $label" );
661 $wgOut->sendCacheControl();
662
663 # Don't send content if it's a HEAD request.
664 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
665 header( 'Content-type: text/plain' );
666 print "$desc\n";
667 }
668 }
669
670 # Converts an Accept-* header into an array mapping string values to quality factors
671 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
672 # No arg means accept anything (per HTTP spec)
673 if( !$accept ) {
674 return array( $def => 1 );
675 }
676
677 $prefs = array();
678
679 $parts = explode( ',', $accept );
680
681 foreach( $parts as $part ) {
682 # FIXME: doesn't deal with params like 'text/html; level=1'
683 @list( $value, $qpart ) = explode( ';', $part );
684 if( !isset( $qpart ) ) {
685 $prefs[$value] = 1;
686 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
687 $prefs[$value] = $match[1];
688 }
689 }
690
691 return $prefs;
692 }
693
694 /* private */ function mimeTypeMatch( $type, $avail ) {
695 if( array_key_exists($type, $avail) ) {
696 return $type;
697 } else {
698 $parts = explode( '/', $type );
699 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
700 return $parts[0] . '/*';
701 } elseif( array_key_exists( '*/*', $avail ) ) {
702 return '*/*';
703 } else {
704 return NULL;
705 }
706 }
707 }
708
709 # FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
710 # XXX: generalize to negotiate other stuff
711 function wfNegotiateType( $cprefs, $sprefs ) {
712 $combine = array();
713
714 foreach( array_keys($sprefs) as $type ) {
715 $parts = explode( '/', $type );
716 if( $parts[1] != '*' ) {
717 $ckey = mimeTypeMatch( $type, $cprefs );
718 if( $ckey ) {
719 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
720 }
721 }
722 }
723
724 foreach( array_keys( $cprefs ) as $type ) {
725 $parts = explode( '/', $type );
726 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
727 $skey = mimeTypeMatch( $type, $sprefs );
728 if( $skey ) {
729 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
730 }
731 }
732 }
733
734 $bestq = 0;
735 $besttype = NULL;
736
737 foreach( array_keys( $combine ) as $type ) {
738 if( $combine[$type] > $bestq ) {
739 $besttype = $type;
740 $bestq = $combine[$type];
741 }
742 }
743
744 return $besttype;
745 }
746
747 # Array lookup
748 # Returns an array where the values in the first array are replaced by the
749 # values in the second array with the corresponding keys
750 function wfArrayLookup( $a, $b )
751 {
752 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
753 }
754
755
756 # Ideally we'd be using actual time fields in the db
757 function wfTimestamp2Unix( $ts ) {
758 return gmmktime( ( (int)substr( $ts, 8, 2) ),
759 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
760 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
761 (int)substr( $ts, 0, 4 ) );
762 }
763
764 function wfUnix2Timestamp( $unixtime ) {
765 return gmdate( 'YmdHis', $unixtime );
766 }
767
768 function wfTimestampNow() {
769 # return NOW
770 return gmdate( 'YmdHis' );
771 }
772
773 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
774 function wfInvertTimestamp( $ts ) {
775 return strtr(
776 $ts,
777 '0123456789',
778 '9876543210'
779 );
780 }
781
782 # Reference-counted warning suppression
783 function wfSuppressWarnings( $end = false ) {
784 static $suppressCount = 0;
785 static $originalLevel = false;
786
787 if ( $end ) {
788 if ( $suppressCount ) {
789 $suppressCount --;
790 if ( !$suppressCount ) {
791 error_reporting( $originalLevel );
792 }
793 }
794 } else {
795 if ( !$suppressCount ) {
796 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
797 }
798 $suppressCount++;
799 }
800 }
801
802 # Restore error level to previous value
803 function wfRestoreWarnings() {
804 wfSuppressWarnings( true );
805 }
806
807 # Autodetect, convert and provide timestamps of various types
808 define('TS_UNIX',0); # Standard unix timestamp (number of seconds since 1 Jan 1970)
809 define('TS_MW',1); # Mediawiki concatenated string timestamp (yyyymmddhhmmss)
810 define('TS_DB',2); # Standard database timestamp (yyyy-mm-dd hh:mm:ss)
811
812 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
813 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
814 # TS_DB
815 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
816 (int)$da[2],(int)$da[3],(int)$da[1]);
817 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
818 # TS_MW
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{1,13})$/",$ts,$datearray)) {
822 # TS_UNIX
823 $uts=$ts;
824 }
825
826 if ($ts==0)
827 $uts=time();
828 switch($outputtype) {
829 case TS_UNIX:
830 return $uts;
831 break;
832 case TS_MW:
833 return gmdate( 'YmdHis', $uts );
834 break;
835 case TS_DB:
836 return gmdate( 'Y-m-d H:i:s', $uts );
837 break;
838 default:
839 return;
840 }
841 }
842
843 function wfIsWindows() {
844 if (substr(php_uname(), 0, 7) == 'Windows') {
845 return true;
846 } else {
847 return false;
848 }
849 }
850
851 ?>