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