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