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