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