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