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