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