58739704ef0a63b318c5935f98702ba550ad8ae7
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 /**
4 * Global functions used everywhere
5 * @package MediaWiki
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
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.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 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 * Where as we got a random seed
84 * @var bool $wgTotalViews
85 */
86 $wgRandomSeeded = false;
87
88 /**
89 * Seed Mersenne Twister
90 * Only necessary in PHP < 4.2.0
91 *
92 * @return bool
93 */
94 function wfSeedRandom() {
95 global $wgRandomSeeded;
96
97 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
98 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
99 mt_srand( $seed );
100 $wgRandomSeeded = true;
101 }
102 }
103
104 /**
105 * Get a random decimal value between 0 and 1, in a way
106 * not likely to give duplicate values for any realistic
107 * number of articles.
108 *
109 * @return string
110 */
111 function wfRandom() {
112 # The maximum random value is "only" 2^31-1, so get two random
113 # values to reduce the chance of dupes
114 $max = mt_getrandmax();
115 $rand = number_format( (mt_rand() * $max + mt_rand())
116 / $max / $max, 12, '.', '' );
117 return $rand;
118 }
119
120 /**
121 * We want / and : to be included as literal characters in our title URLs.
122 * %2F in the page titles seems to fatally break for some reason.
123 *
124 * @param string $s
125 * @return string
126 */
127 function wfUrlencode ( $s ) {
128 $s = urlencode( $s );
129 $s = preg_replace( '/%3[Aa]/', ':', $s );
130 $s = preg_replace( '/%2[Ff]/', '/', $s );
131
132 return $s;
133 }
134
135 /**
136 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
137 * In normal operation this is a NOP.
138 *
139 * Controlling globals:
140 * $wgDebugLogFile - points to the log file
141 * $wgProfileOnly - if set, normal debug messages will not be recorded.
142 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
143 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
144 *
145 * @param string $text
146 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
147 */
148 function wfDebug( $text, $logonly = false ) {
149 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
150
151 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
152 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
153 return;
154 }
155
156 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
157 $wgOut->debug( $text );
158 }
159 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
160 # Strip unprintables; they can switch terminal modes when binary data
161 # gets dumped, which is pretty annoying.
162 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
163 @error_log( $text, 3, $wgDebugLogFile );
164 }
165 }
166
167 /**
168 * Log for database errors
169 * @param string $text Database error message.
170 */
171 function wfLogDBError( $text ) {
172 global $wgDBerrorLog;
173 if ( $wgDBerrorLog ) {
174 $text = date('D M j G:i:s T Y') . "\t".$text;
175 error_log( $text, 3, $wgDBerrorLog );
176 }
177 }
178
179 /**
180 * @todo document
181 */
182 function logProfilingData() {
183 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
184 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
185 $now = wfTime();
186
187 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
188 $start = (float)$sec + (float)$usec;
189 $elapsed = $now - $start;
190 if ( $wgProfiling ) {
191 $prof = wfGetProfilingOutput( $start, $elapsed );
192 $forward = '';
193 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
194 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
195 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
196 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
197 if( !empty( $_SERVER['HTTP_FROM'] ) )
198 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
199 if( $forward )
200 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
201 if( $wgUser->isAnon() )
202 $forward .= ' anon';
203 $log = sprintf( "%s\t%04.3f\t%s\n",
204 gmdate( 'YmdHis' ), $elapsed,
205 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
206 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
207 error_log( $log . $prof, 3, $wgDebugLogFile );
208 }
209 }
210 }
211
212 /**
213 * Check if the wiki read-only lock file is present. This can be used to lock
214 * off editing functions, but doesn't guarantee that the database will not be
215 * modified.
216 * @return bool
217 */
218 function wfReadOnly() {
219 global $wgReadOnlyFile, $wgReadOnly;
220
221 if ( $wgReadOnly ) {
222 return true;
223 }
224 if ( '' == $wgReadOnlyFile ) {
225 return false;
226 }
227 return is_file( $wgReadOnlyFile );
228 }
229
230
231 /**
232 * Get a message from anywhere, for the current user language
233 *
234 * @param string
235 */
236 function wfMsg( $key ) {
237 $args = func_get_args();
238 array_shift( $args );
239 return wfMsgReal( $key, $args, true );
240 }
241
242 /**
243 * Get a message from anywhere, for the current global language
244 */
245 function wfMsgForContent( $key ) {
246 global $wgForceUIMsgAsContentMsg;
247 $args = func_get_args();
248 array_shift( $args );
249 $forcontent = true;
250 if( is_array( $wgForceUIMsgAsContentMsg ) &&
251 in_array( $key, $wgForceUIMsgAsContentMsg ) )
252 $forcontent = false;
253 return wfMsgReal( $key, $args, true, $forcontent );
254 }
255
256 /**
257 * Get a message from the language file, for the UI elements
258 */
259 function wfMsgNoDB( $key ) {
260 $args = func_get_args();
261 array_shift( $args );
262 return wfMsgReal( $key, $args, false );
263 }
264
265 /**
266 * Get a message from the language file, for the content
267 */
268 function wfMsgNoDBForContent( $key ) {
269 global $wgForceUIMsgAsContentMsg;
270 $args = func_get_args();
271 array_shift( $args );
272 $forcontent = true;
273 if( is_array( $wgForceUIMsgAsContentMsg ) &&
274 in_array( $key, $wgForceUIMsgAsContentMsg ) )
275 $forcontent = false;
276 return wfMsgReal( $key, $args, false, $forcontent );
277 }
278
279
280 /**
281 * Really get a message
282 */
283 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
284 $fname = 'wfMsgReal';
285 wfProfileIn( $fname );
286
287 $message = wfMsgGetKey( $key, $useDB, $forContent );
288 $message = wfMsgReplaceArgs( $message, $args );
289 wfProfileOut( $fname );
290 return $message;
291 }
292
293 /**
294 * Fetch a message string value, but don't replace any keys yet.
295 * @param string $key
296 * @param bool $useDB
297 * @param bool $forContent
298 * @return string
299 * @access private
300 */
301 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
302 global $wgParser, $wgMsgParserOptions;
303 global $wgContLang, $wgLanguageCode;
304 global $wgMessageCache, $wgLang;
305
306 if( is_object( $wgMessageCache ) ) {
307 $message = $wgMessageCache->get( $key, $useDB, $forContent );
308 } else {
309 if( $forContent ) {
310 $lang = &$wgContLang;
311 } else {
312 $lang = &$wgLang;
313 }
314
315 wfSuppressWarnings();
316
317 if( is_object( $lang ) ) {
318 $message = $lang->getMessage( $key );
319 } else {
320 $message = '';
321 }
322 wfRestoreWarnings();
323 if(!$message)
324 $message = Language::getMessage($key);
325 if(strstr($message, '{{' ) !== false) {
326 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
327 }
328 }
329 return $message;
330 }
331
332 /**
333 * Replace message parameter keys on the given formatted output.
334 *
335 * @param string $message
336 * @param array $args
337 * @return string
338 * @access private
339 */
340 function wfMsgReplaceArgs( $message, $args ) {
341 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
342
343 # Fix windows line-endings
344 # Some messages are split with explode("\n", $msg)
345 $message = str_replace( "\r", '', $message );
346
347 # Replace arguments
348 if( count( $args ) ) {
349 $message = str_replace( $replacementKeys, $args, $message );
350 }
351 return $message;
352 }
353
354 /**
355 * Return an HTML-escaped version of a message.
356 * Parameter replacements, if any, are done *after* the HTML-escaping,
357 * so parameters may contain HTML (eg links or form controls). Be sure
358 * to pre-escape them if you really do want plaintext, or just wrap
359 * the whole thing in htmlspecialchars().
360 *
361 * @param string $key
362 * @param string ... parameters
363 * @return string
364 */
365 function wfMsgHtml( $key ) {
366 $args = func_get_args();
367 array_shift( $args );
368 return wfMsgReplaceArgs(
369 htmlspecialchars( wfMsgGetKey( $key, $args, true ) ),
370 $args );
371 }
372
373 /**
374 * Just like exit() but makes a note of it.
375 * Commits open transactions except if the error parameter is set
376 */
377 function wfAbruptExit( $error = false ){
378 global $wgLoadBalancer;
379 static $called = false;
380 if ( $called ){
381 exit();
382 }
383 $called = true;
384
385 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
386 $bt = debug_backtrace();
387 for($i = 0; $i < count($bt) ; $i++){
388 $file = $bt[$i]['file'];
389 $line = $bt[$i]['line'];
390 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
391 }
392 } else {
393 wfDebug('WARNING: Abrupt exit\n');
394 }
395 if ( !$error ) {
396 $wgLoadBalancer->closeAll();
397 }
398 exit();
399 }
400
401 /**
402 * @todo document
403 */
404 function wfErrorExit() {
405 wfAbruptExit( true );
406 }
407
408 /**
409 * Die with a backtrace
410 * This is meant as a debugging aid to track down where bad data comes from.
411 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
412 *
413 * @param string $msg Message shown when dieing.
414 */
415 function wfDebugDieBacktrace( $msg = '' ) {
416 global $wgCommandLineMode;
417
418 $backtrace = wfBacktrace();
419 if ( $backtrace !== false ) {
420 if ( $wgCommandLineMode ) {
421 $msg .= "\nBacktrace:\n$backtrace";
422 } else {
423 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
424 }
425 }
426 die( $msg );
427 }
428
429 function wfBacktrace() {
430 global $wgCommandLineMode;
431 if ( !function_exists( 'debug_backtrace' ) ) {
432 return false;
433 }
434
435 if ( $wgCommandLineMode ) {
436 $msg = '';
437 } else {
438 $msg = "<ul>\n";
439 }
440 $backtrace = debug_backtrace();
441 foreach( $backtrace as $call ) {
442 if( isset( $call['file'] ) ) {
443 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
444 $file = $f[count($f)-1];
445 } else {
446 $file = '-';
447 }
448 if( isset( $call['line'] ) ) {
449 $line = $call['line'];
450 } else {
451 $line = '-';
452 }
453 if ( $wgCommandLineMode ) {
454 $msg .= "$file line $line calls ";
455 } else {
456 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
457 }
458 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
459 $msg .= $call['function'] . '()';
460
461 if ( $wgCommandLineMode ) {
462 $msg .= "\n";
463 } else {
464 $msg .= "</li>\n";
465 }
466 }
467 if ( $wgCommandLineMode ) {
468 $msg .= "\n";
469 } else {
470 $msg .= "</ul>\n";
471 }
472
473 return $msg;
474 }
475
476
477 /* Some generic result counters, pulled out of SearchEngine */
478
479
480 /**
481 * @todo document
482 */
483 function wfShowingResults( $offset, $limit ) {
484 global $wgLang;
485 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
486 }
487
488 /**
489 * @todo document
490 */
491 function wfShowingResultsNum( $offset, $limit, $num ) {
492 global $wgLang;
493 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
494 }
495
496 /**
497 * @todo document
498 */
499 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
500 global $wgUser, $wgLang;
501 $fmtLimit = $wgLang->formatNum( $limit );
502 $prev = wfMsg( 'prevn', $fmtLimit );
503 $next = wfMsg( 'nextn', $fmtLimit );
504
505 if( is_object( $link ) ) {
506 $title =& $link;
507 } else {
508 $title =& Title::newFromText( $link );
509 if( is_null( $title ) ) {
510 return false;
511 }
512 }
513
514 $sk = $wgUser->getSkin();
515 if ( 0 != $offset ) {
516 $po = $offset - $limit;
517 if ( $po < 0 ) { $po = 0; }
518 $q = "limit={$limit}&offset={$po}";
519 if ( '' != $query ) { $q .= '&'.$query; }
520 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
521 } else { $plink = $prev; }
522
523 $no = $offset + $limit;
524 $q = 'limit='.$limit.'&offset='.$no;
525 if ( '' != $query ) { $q .= '&'.$query; }
526
527 if ( $atend ) {
528 $nlink = $next;
529 } else {
530 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
531 }
532 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
533 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
534 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
535 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
536 wfNumLink( $offset, 500, $title, $query );
537
538 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
539 }
540
541 /**
542 * @todo document
543 */
544 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
545 global $wgUser, $wgLang;
546 if ( '' == $query ) { $q = ''; }
547 else { $q = $query.'&'; }
548 $q .= 'limit='.$limit.'&offset='.$offset;
549
550 $fmtLimit = $wgLang->formatNum( $limit );
551 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
552 return $s;
553 }
554
555 /**
556 * @todo document
557 * @todo FIXME: we may want to blacklist some broken browsers
558 *
559 * @return bool Whereas client accept gzip compression
560 */
561 function wfClientAcceptsGzip() {
562 global $wgUseGzip;
563 if( $wgUseGzip ) {
564 # FIXME: we may want to blacklist some broken browsers
565 if( preg_match(
566 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
567 $_SERVER['HTTP_ACCEPT_ENCODING'],
568 $m ) ) {
569 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
570 wfDebug( " accepts gzip\n" );
571 return true;
572 }
573 }
574 return false;
575 }
576
577 /**
578 * Yay, more global functions!
579 */
580 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
581 global $wgRequest;
582 return $wgRequest->getLimitOffset( $deflimit, $optionname );
583 }
584
585 /**
586 * Escapes the given text so that it may be output using addWikiText()
587 * without any linking, formatting, etc. making its way through. This
588 * is achieved by substituting certain characters with HTML entities.
589 * As required by the callers, <nowiki> is not used. It currently does
590 * not filter out characters which have special meaning only at the
591 * start of a line, such as "*".
592 *
593 * @param string $text Text to be escaped
594 */
595 function wfEscapeWikiText( $text ) {
596 $text = str_replace(
597 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
598 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
599 htmlspecialchars($text) );
600 return $text;
601 }
602
603 /**
604 * @todo document
605 */
606 function wfQuotedPrintable( $string, $charset = '' ) {
607 # Probably incomplete; see RFC 2045
608 if( empty( $charset ) ) {
609 global $wgInputEncoding;
610 $charset = $wgInputEncoding;
611 }
612 $charset = strtoupper( $charset );
613 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
614
615 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
616 $replace = $illegal . '\t ?_';
617 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
618 $out = "=?$charset?Q?";
619 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
620 $out .= '?=';
621 return $out;
622 }
623
624 /**
625 * Returns an escaped string suitable for inclusion in a string literal
626 * for JavaScript source code.
627 * Illegal control characters are assumed not to be present.
628 *
629 * @param string $string
630 * @return string
631 */
632 function wfEscapeJsString( $string ) {
633 // See ECMA 262 section 7.8.4 for string literal format
634 $pairs = array(
635 "\\" => "\\\\",
636 "\"" => "\\\"",
637 "\'" => "\\\'",
638 "\n" => "\\n",
639 "\r" => "\\r",
640
641 # To avoid closing the element or CDATA section
642 "<" => "\\x3c",
643 ">" => "\\x3e",
644 );
645 return strtr( $string, $pairs );
646 }
647
648 /**
649 * @todo document
650 * @return float
651 */
652 function wfTime() {
653 $st = explode( ' ', microtime() );
654 return (float)$st[0] + (float)$st[1];
655 }
656
657 /**
658 * Changes the first character to an HTML entity
659 */
660 function wfHtmlEscapeFirst( $text ) {
661 $ord = ord($text);
662 $newText = substr($text, 1);
663 return "&#$ord;$newText";
664 }
665
666 /**
667 * Sets dest to source and returns the original value of dest
668 * If source is NULL, it just returns the value, it doesn't set the variable
669 */
670 function wfSetVar( &$dest, $source ) {
671 $temp = $dest;
672 if ( !is_null( $source ) ) {
673 $dest = $source;
674 }
675 return $temp;
676 }
677
678 /**
679 * As for wfSetVar except setting a bit
680 */
681 function wfSetBit( &$dest, $bit, $state = true ) {
682 $temp = (bool)($dest & $bit );
683 if ( !is_null( $state ) ) {
684 if ( $state ) {
685 $dest |= $bit;
686 } else {
687 $dest &= ~$bit;
688 }
689 }
690 return $temp;
691 }
692
693 /**
694 * This function takes two arrays as input, and returns a CGI-style string, e.g.
695 * "days=7&limit=100". Options in the first array override options in the second.
696 * Options set to "" will not be output.
697 */
698 function wfArrayToCGI( $array1, $array2 = NULL )
699 {
700 if ( !is_null( $array2 ) ) {
701 $array1 = $array1 + $array2;
702 }
703
704 $cgi = '';
705 foreach ( $array1 as $key => $value ) {
706 if ( '' !== $value ) {
707 if ( '' != $cgi ) {
708 $cgi .= '&';
709 }
710 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
711 }
712 }
713 return $cgi;
714 }
715
716 /**
717 * This is obsolete, use SquidUpdate::purge()
718 * @deprecated
719 */
720 function wfPurgeSquidServers ($urlArr) {
721 SquidUpdate::purge( $urlArr );
722 }
723
724 /**
725 * Windows-compatible version of escapeshellarg()
726 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
727 * function puts single quotes in regardless of OS
728 */
729 function wfEscapeShellArg( ) {
730 $args = func_get_args();
731 $first = true;
732 $retVal = '';
733 foreach ( $args as $arg ) {
734 if ( !$first ) {
735 $retVal .= ' ';
736 } else {
737 $first = false;
738 }
739
740 if ( wfIsWindows() ) {
741 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
742 } else {
743 $retVal .= escapeshellarg( $arg );
744 }
745 }
746 return $retVal;
747 }
748
749 /**
750 * wfMerge attempts to merge differences between three texts.
751 * Returns true for a clean merge and false for failure or a conflict.
752 */
753 function wfMerge( $old, $mine, $yours, &$result ){
754 global $wgDiff3;
755
756 # This check may also protect against code injection in
757 # case of broken installations.
758 if(! file_exists( $wgDiff3 ) ){
759 return false;
760 }
761
762 # Make temporary files
763 $td = wfTempDir();
764 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
765 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
766 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
767
768 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
769 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
770 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
771
772 # Check for a conflict
773 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
774 wfEscapeShellArg( $mytextName ) . ' ' .
775 wfEscapeShellArg( $oldtextName ) . ' ' .
776 wfEscapeShellArg( $yourtextName );
777 $handle = popen( $cmd, 'r' );
778
779 if( fgets( $handle, 1024 ) ){
780 $conflict = true;
781 } else {
782 $conflict = false;
783 }
784 pclose( $handle );
785
786 # Merge differences
787 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
788 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
789 $handle = popen( $cmd, 'r' );
790 $result = '';
791 do {
792 $data = fread( $handle, 8192 );
793 if ( strlen( $data ) == 0 ) {
794 break;
795 }
796 $result .= $data;
797 } while ( true );
798 pclose( $handle );
799 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
800 return ! $conflict;
801 }
802
803 /**
804 * @todo document
805 */
806 function wfVarDump( $var ) {
807 global $wgOut;
808 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
809 if ( headers_sent() || !@is_object( $wgOut ) ) {
810 print $s;
811 } else {
812 $wgOut->addHTML( $s );
813 }
814 }
815
816 /**
817 * Provide a simple HTTP error.
818 */
819 function wfHttpError( $code, $label, $desc ) {
820 global $wgOut;
821 $wgOut->disable();
822 header( "HTTP/1.0 $code $label" );
823 header( "Status: $code $label" );
824 $wgOut->sendCacheControl();
825
826 header( 'Content-type: text/html' );
827 print "<html><head><title>" .
828 htmlspecialchars( $label ) .
829 "</title></head><body><h1>" .
830 htmlspecialchars( $label ) .
831 "</h1><p>" .
832 htmlspecialchars( $desc ) .
833 "</p></body></html>\n";
834 }
835
836 /**
837 * Converts an Accept-* header into an array mapping string values to quality
838 * factors
839 */
840 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
841 # No arg means accept anything (per HTTP spec)
842 if( !$accept ) {
843 return array( $def => 1 );
844 }
845
846 $prefs = array();
847
848 $parts = explode( ',', $accept );
849
850 foreach( $parts as $part ) {
851 # FIXME: doesn't deal with params like 'text/html; level=1'
852 @list( $value, $qpart ) = explode( ';', $part );
853 if( !isset( $qpart ) ) {
854 $prefs[$value] = 1;
855 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
856 $prefs[$value] = $match[1];
857 }
858 }
859
860 return $prefs;
861 }
862
863 /**
864 * Checks if a given MIME type matches any of the keys in the given
865 * array. Basic wildcards are accepted in the array keys.
866 *
867 * Returns the matching MIME type (or wildcard) if a match, otherwise
868 * NULL if no match.
869 *
870 * @param string $type
871 * @param array $avail
872 * @return string
873 * @access private
874 */
875 function mimeTypeMatch( $type, $avail ) {
876 if( array_key_exists($type, $avail) ) {
877 return $type;
878 } else {
879 $parts = explode( '/', $type );
880 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
881 return $parts[0] . '/*';
882 } elseif( array_key_exists( '*/*', $avail ) ) {
883 return '*/*';
884 } else {
885 return NULL;
886 }
887 }
888 }
889
890 /**
891 * Returns the 'best' match between a client's requested internet media types
892 * and the server's list of available types. Each list should be an associative
893 * array of type to preference (preference is a float between 0.0 and 1.0).
894 * Wildcards in the types are acceptable.
895 *
896 * @param array $cprefs Client's acceptable type list
897 * @param array $sprefs Server's offered types
898 * @return string
899 *
900 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
901 * XXX: generalize to negotiate other stuff
902 */
903 function wfNegotiateType( $cprefs, $sprefs ) {
904 $combine = array();
905
906 foreach( array_keys($sprefs) as $type ) {
907 $parts = explode( '/', $type );
908 if( $parts[1] != '*' ) {
909 $ckey = mimeTypeMatch( $type, $cprefs );
910 if( $ckey ) {
911 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
912 }
913 }
914 }
915
916 foreach( array_keys( $cprefs ) as $type ) {
917 $parts = explode( '/', $type );
918 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
919 $skey = mimeTypeMatch( $type, $sprefs );
920 if( $skey ) {
921 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
922 }
923 }
924 }
925
926 $bestq = 0;
927 $besttype = NULL;
928
929 foreach( array_keys( $combine ) as $type ) {
930 if( $combine[$type] > $bestq ) {
931 $besttype = $type;
932 $bestq = $combine[$type];
933 }
934 }
935
936 return $besttype;
937 }
938
939 /**
940 * Array lookup
941 * Returns an array where the values in the first array are replaced by the
942 * values in the second array with the corresponding keys
943 *
944 * @return array
945 */
946 function wfArrayLookup( $a, $b ) {
947 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
948 }
949
950 /**
951 * Convenience function; returns MediaWiki timestamp for the present time.
952 * @return string
953 */
954 function wfTimestampNow() {
955 # return NOW
956 return wfTimestamp( TS_MW, time() );
957 }
958
959 /**
960 * Reference-counted warning suppression
961 */
962 function wfSuppressWarnings( $end = false ) {
963 static $suppressCount = 0;
964 static $originalLevel = false;
965
966 if ( $end ) {
967 if ( $suppressCount ) {
968 $suppressCount --;
969 if ( !$suppressCount ) {
970 error_reporting( $originalLevel );
971 }
972 }
973 } else {
974 if ( !$suppressCount ) {
975 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
976 }
977 $suppressCount++;
978 }
979 }
980
981 /**
982 * Restore error level to previous value
983 */
984 function wfRestoreWarnings() {
985 wfSuppressWarnings( true );
986 }
987
988 # Autodetect, convert and provide timestamps of various types
989
990 /**
991 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
992 */
993 define('TS_UNIX', 0);
994
995 /**
996 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
997 */
998 define('TS_MW', 1);
999
1000 /**
1001 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1002 */
1003 define('TS_DB', 2);
1004
1005 /**
1006 * RFC 2822 format, for E-mail and HTTP headers
1007 */
1008 define('TS_RFC2822', 3);
1009
1010 /**
1011 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1012 *
1013 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1014 * DateTime tag and page 36 for the DateTimeOriginal and
1015 * DateTimeDigitized tags.
1016 */
1017 define('TS_EXIF', 4);
1018
1019
1020 /**
1021 * @param mixed $outputtype A timestamp in one of the supported formats, the
1022 * function will autodetect which format is supplied
1023 and act accordingly.
1024 * @return string Time in the format specified in $outputtype
1025 */
1026 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1027 if ($ts==0) {
1028 $uts=time();
1029 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1030 # TS_DB
1031 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1032 (int)$da[2],(int)$da[3],(int)$da[1]);
1033 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1034 # TS_EXIF
1035 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1036 (int)$da[2],(int)$da[3],(int)$da[1]);
1037 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1038 # TS_MW
1039 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1040 (int)$da[2],(int)$da[3],(int)$da[1]);
1041 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1042 # TS_UNIX
1043 $uts=$ts;
1044 } else {
1045 # Bogus value; fall back to the epoch...
1046 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1047 $uts = 0;
1048 }
1049
1050
1051 switch($outputtype) {
1052 case TS_UNIX:
1053 return $uts;
1054 case TS_MW:
1055 return gmdate( 'YmdHis', $uts );
1056 case TS_DB:
1057 return gmdate( 'Y-m-d H:i:s', $uts );
1058 // This shouldn't ever be used, but is included for completeness
1059 case TS_EXIF:
1060 return gmdate( 'Y:m:d H:i:s', $uts );
1061 case TS_RFC2822:
1062 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1063 default:
1064 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1065 }
1066 }
1067
1068 /**
1069 * Return a formatted timestamp, or null if input is null.
1070 * For dealing with nullable timestamp columns in the database.
1071 * @param int $outputtype
1072 * @param string $ts
1073 * @return string
1074 */
1075 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1076 if( is_null( $ts ) ) {
1077 return null;
1078 } else {
1079 return wfTimestamp( $outputtype, $ts );
1080 }
1081 }
1082
1083 /**
1084 * Check where as the operating system is Windows
1085 *
1086 * @return bool True if it's windows, False otherwise.
1087 */
1088 function wfIsWindows() {
1089 if (substr(php_uname(), 0, 7) == 'Windows') {
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
1096 /**
1097 * Swap two variables
1098 */
1099 function swap( &$x, &$y ) {
1100 $z = $x;
1101 $x = $y;
1102 $y = $z;
1103 }
1104
1105 function wfGetSiteNotice() {
1106 global $wgSiteNotice, $wgTitle, $wgOut;
1107 $fname = 'wfGetSiteNotice';
1108 wfProfileIn( $fname );
1109
1110 $notice = wfMsg( 'sitenotice' );
1111 if($notice == '&lt;sitenotice&gt;') $notice = '';
1112 # Allow individual wikis to turn it off
1113 if ( $notice == '-' ) {
1114 $notice = '';
1115 } else {
1116 if ($notice == '') {
1117 $notice = $wgSiteNotice;
1118 }
1119 if($notice != '-' && $notice != '') {
1120 $specialparser = new Parser();
1121 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1122 $notice = $parserOutput->getText();
1123 }
1124 }
1125 wfProfileOut( $fname );
1126 return $notice;
1127 }
1128
1129 /**
1130 * Format an XML element with given attributes and, optionally, text content.
1131 * Element and attribute names are assumed to be ready for literal inclusion.
1132 * Strings are assumed to not contain XML-illegal characters; special
1133 * characters (<, >, &) are escaped but illegals are not touched.
1134 *
1135 * @param string $element
1136 * @param array $attribs Name=>value pairs. Values will be escaped.
1137 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1138 * @return string
1139 */
1140 function wfElement( $element, $attribs = null, $contents = '') {
1141 $out = '<' . $element;
1142 if( !is_null( $attribs ) ) {
1143 foreach( $attribs as $name => $val ) {
1144 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1145 }
1146 }
1147 if( is_null( $contents ) ) {
1148 $out .= '>';
1149 } else {
1150 if( $contents == '' ) {
1151 $out .= ' />';
1152 } else {
1153 $out .= '>';
1154 $out .= htmlspecialchars( $contents );
1155 $out .= "</$element>";
1156 }
1157 }
1158 return $out;
1159 }
1160
1161 /**
1162 * Format an XML element as with wfElement(), but run text through the
1163 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1164 * is passed.
1165 *
1166 * @param string $element
1167 * @param array $attribs Name=>value pairs. Values will be escaped.
1168 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1169 * @return string
1170 */
1171 function wfElementClean( $element, $attribs = array(), $contents = '') {
1172 if( $attribs ) {
1173 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1174 }
1175 if( $contents ) {
1176 $contents = UtfNormal::cleanUp( $contents );
1177 }
1178 return wfElement( $element, $attribs, $contents );
1179 }
1180
1181 /** Global singleton instance of MimeMagic. This is initialized on demand,
1182 * please always use the wfGetMimeMagic() function to get the instance.
1183 *
1184 * @private
1185 */
1186 $wgMimeMagic= NULL;
1187
1188 /** Factory functions for the global MimeMagic object.
1189 * This function always returns the same singleton instance of MimeMagic.
1190 * That objects will be instantiated on the first call to this function.
1191 * If needed, the MimeMagic.php file is automatically included by this function.
1192 * @return MimeMagic the global MimeMagic objects.
1193 */
1194 function &wfGetMimeMagic() {
1195 global $wgMimeMagic;
1196
1197 if (!is_null($wgMimeMagic)) {
1198 return $wgMimeMagic;
1199 }
1200
1201 if (!class_exists("MimeMagic")) {
1202 #include on demand
1203 require_once("MimeMagic.php");
1204 }
1205
1206 $wgMimeMagic= new MimeMagic();
1207
1208 return $wgMimeMagic;
1209 }
1210
1211
1212 /**
1213 * Tries to get the system directory for temporary files.
1214 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1215 * and if none are set /tmp is returned as the generic Unix default.
1216 *
1217 * NOTE: When possible, use the tempfile() function to create temporary
1218 * files to avoid race conditions on file creation, etc.
1219 *
1220 * @return string
1221 */
1222 function wfTempDir() {
1223 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1224 $tmp = getenv( 'TMPDIR' );
1225 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1226 return $tmp;
1227 }
1228 }
1229 # Hope this is Unix of some kind!
1230 return '/tmp';
1231 }
1232
1233 /**
1234 * Make directory, and make all parent directories if they don't exist
1235 */
1236 function wfMkdirParents( $fullDir, $mode ) {
1237 $parts = explode( '/', $fullDir );
1238 $path = '';
1239 $success = false;
1240 foreach ( $parts as $dir ) {
1241 $path .= $dir . '/';
1242 if ( !is_dir( $path ) ) {
1243 if ( !mkdir( $path, $mode ) ) {
1244 return false;
1245 }
1246 }
1247 }
1248 return true;
1249 }
1250
1251 ?>