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