faster read-only mode
[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 die( $msg );
435 }
436
437 function wfBacktrace() {
438 global $wgCommandLineMode;
439 if ( !function_exists( 'debug_backtrace' ) ) {
440 return false;
441 }
442
443 if ( $wgCommandLineMode ) {
444 $msg = '';
445 } else {
446 $msg = "<ul>\n";
447 }
448 $backtrace = debug_backtrace();
449 foreach( $backtrace as $call ) {
450 if( isset( $call['file'] ) ) {
451 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
452 $file = $f[count($f)-1];
453 } else {
454 $file = '-';
455 }
456 if( isset( $call['line'] ) ) {
457 $line = $call['line'];
458 } else {
459 $line = '-';
460 }
461 if ( $wgCommandLineMode ) {
462 $msg .= "$file line $line calls ";
463 } else {
464 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
465 }
466 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
467 $msg .= $call['function'] . '()';
468
469 if ( $wgCommandLineMode ) {
470 $msg .= "\n";
471 } else {
472 $msg .= "</li>\n";
473 }
474 }
475 if ( $wgCommandLineMode ) {
476 $msg .= "\n";
477 } else {
478 $msg .= "</ul>\n";
479 }
480
481 return $msg;
482 }
483
484
485 /* Some generic result counters, pulled out of SearchEngine */
486
487
488 /**
489 * @todo document
490 */
491 function wfShowingResults( $offset, $limit ) {
492 global $wgLang;
493 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
494 }
495
496 /**
497 * @todo document
498 */
499 function wfShowingResultsNum( $offset, $limit, $num ) {
500 global $wgLang;
501 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
502 }
503
504 /**
505 * @todo document
506 */
507 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
508 global $wgUser, $wgLang;
509 $fmtLimit = $wgLang->formatNum( $limit );
510 $prev = wfMsg( 'prevn', $fmtLimit );
511 $next = wfMsg( 'nextn', $fmtLimit );
512
513 if( is_object( $link ) ) {
514 $title =& $link;
515 } else {
516 $title =& Title::newFromText( $link );
517 if( is_null( $title ) ) {
518 return false;
519 }
520 }
521
522 $sk = $wgUser->getSkin();
523 if ( 0 != $offset ) {
524 $po = $offset - $limit;
525 if ( $po < 0 ) { $po = 0; }
526 $q = "limit={$limit}&offset={$po}";
527 if ( '' != $query ) { $q .= '&'.$query; }
528 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
529 } else { $plink = $prev; }
530
531 $no = $offset + $limit;
532 $q = 'limit='.$limit.'&offset='.$no;
533 if ( '' != $query ) { $q .= '&'.$query; }
534
535 if ( $atend ) {
536 $nlink = $next;
537 } else {
538 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
539 }
540 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
541 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
542 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
543 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
544 wfNumLink( $offset, 500, $title, $query );
545
546 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
547 }
548
549 /**
550 * @todo document
551 */
552 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
553 global $wgUser, $wgLang;
554 if ( '' == $query ) { $q = ''; }
555 else { $q = $query.'&'; }
556 $q .= 'limit='.$limit.'&offset='.$offset;
557
558 $fmtLimit = $wgLang->formatNum( $limit );
559 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
560 return $s;
561 }
562
563 /**
564 * @todo document
565 * @todo FIXME: we may want to blacklist some broken browsers
566 *
567 * @return bool Whereas client accept gzip compression
568 */
569 function wfClientAcceptsGzip() {
570 global $wgUseGzip;
571 if( $wgUseGzip ) {
572 # FIXME: we may want to blacklist some broken browsers
573 if( preg_match(
574 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
575 $_SERVER['HTTP_ACCEPT_ENCODING'],
576 $m ) ) {
577 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
578 wfDebug( " accepts gzip\n" );
579 return true;
580 }
581 }
582 return false;
583 }
584
585 /**
586 * Yay, more global functions!
587 */
588 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
589 global $wgRequest;
590 return $wgRequest->getLimitOffset( $deflimit, $optionname );
591 }
592
593 /**
594 * Escapes the given text so that it may be output using addWikiText()
595 * without any linking, formatting, etc. making its way through. This
596 * is achieved by substituting certain characters with HTML entities.
597 * As required by the callers, <nowiki> is not used. It currently does
598 * not filter out characters which have special meaning only at the
599 * start of a line, such as "*".
600 *
601 * @param string $text Text to be escaped
602 */
603 function wfEscapeWikiText( $text ) {
604 $text = str_replace(
605 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
606 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
607 htmlspecialchars($text) );
608 return $text;
609 }
610
611 /**
612 * @todo document
613 */
614 function wfQuotedPrintable( $string, $charset = '' ) {
615 # Probably incomplete; see RFC 2045
616 if( empty( $charset ) ) {
617 global $wgInputEncoding;
618 $charset = $wgInputEncoding;
619 }
620 $charset = strtoupper( $charset );
621 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
622
623 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
624 $replace = $illegal . '\t ?_';
625 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
626 $out = "=?$charset?Q?";
627 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
628 $out .= '?=';
629 return $out;
630 }
631
632 /**
633 * Returns an escaped string suitable for inclusion in a string literal
634 * for JavaScript source code.
635 * Illegal control characters are assumed not to be present.
636 *
637 * @param string $string
638 * @return string
639 */
640 function wfEscapeJsString( $string ) {
641 // See ECMA 262 section 7.8.4 for string literal format
642 $pairs = array(
643 "\\" => "\\\\",
644 "\"" => "\\\"",
645 "\'" => "\\\'",
646 "\n" => "\\n",
647 "\r" => "\\r",
648
649 # To avoid closing the element or CDATA section
650 "<" => "\\x3c",
651 ">" => "\\x3e",
652 );
653 return strtr( $string, $pairs );
654 }
655
656 /**
657 * @todo document
658 * @return float
659 */
660 function wfTime() {
661 $st = explode( ' ', microtime() );
662 return (float)$st[0] + (float)$st[1];
663 }
664
665 /**
666 * Changes the first character to an HTML entity
667 */
668 function wfHtmlEscapeFirst( $text ) {
669 $ord = ord($text);
670 $newText = substr($text, 1);
671 return "&#$ord;$newText";
672 }
673
674 /**
675 * Sets dest to source and returns the original value of dest
676 * If source is NULL, it just returns the value, it doesn't set the variable
677 */
678 function wfSetVar( &$dest, $source ) {
679 $temp = $dest;
680 if ( !is_null( $source ) ) {
681 $dest = $source;
682 }
683 return $temp;
684 }
685
686 /**
687 * As for wfSetVar except setting a bit
688 */
689 function wfSetBit( &$dest, $bit, $state = true ) {
690 $temp = (bool)($dest & $bit );
691 if ( !is_null( $state ) ) {
692 if ( $state ) {
693 $dest |= $bit;
694 } else {
695 $dest &= ~$bit;
696 }
697 }
698 return $temp;
699 }
700
701 /**
702 * This function takes two arrays as input, and returns a CGI-style string, e.g.
703 * "days=7&limit=100". Options in the first array override options in the second.
704 * Options set to "" will not be output.
705 */
706 function wfArrayToCGI( $array1, $array2 = NULL )
707 {
708 if ( !is_null( $array2 ) ) {
709 $array1 = $array1 + $array2;
710 }
711
712 $cgi = '';
713 foreach ( $array1 as $key => $value ) {
714 if ( '' !== $value ) {
715 if ( '' != $cgi ) {
716 $cgi .= '&';
717 }
718 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
719 }
720 }
721 return $cgi;
722 }
723
724 /**
725 * This is obsolete, use SquidUpdate::purge()
726 * @deprecated
727 */
728 function wfPurgeSquidServers ($urlArr) {
729 SquidUpdate::purge( $urlArr );
730 }
731
732 /**
733 * Windows-compatible version of escapeshellarg()
734 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
735 * function puts single quotes in regardless of OS
736 */
737 function wfEscapeShellArg( ) {
738 $args = func_get_args();
739 $first = true;
740 $retVal = '';
741 foreach ( $args as $arg ) {
742 if ( !$first ) {
743 $retVal .= ' ';
744 } else {
745 $first = false;
746 }
747
748 if ( wfIsWindows() ) {
749 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
750 } else {
751 $retVal .= escapeshellarg( $arg );
752 }
753 }
754 return $retVal;
755 }
756
757 /**
758 * wfMerge attempts to merge differences between three texts.
759 * Returns true for a clean merge and false for failure or a conflict.
760 */
761 function wfMerge( $old, $mine, $yours, &$result ){
762 global $wgDiff3;
763
764 # This check may also protect against code injection in
765 # case of broken installations.
766 if(! file_exists( $wgDiff3 ) ){
767 return false;
768 }
769
770 # Make temporary files
771 $td = wfTempDir();
772 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
773 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
774 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
775
776 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
777 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
778 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
779
780 # Check for a conflict
781 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
782 wfEscapeShellArg( $mytextName ) . ' ' .
783 wfEscapeShellArg( $oldtextName ) . ' ' .
784 wfEscapeShellArg( $yourtextName );
785 $handle = popen( $cmd, 'r' );
786
787 if( fgets( $handle, 1024 ) ){
788 $conflict = true;
789 } else {
790 $conflict = false;
791 }
792 pclose( $handle );
793
794 # Merge differences
795 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
796 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
797 $handle = popen( $cmd, 'r' );
798 $result = '';
799 do {
800 $data = fread( $handle, 8192 );
801 if ( strlen( $data ) == 0 ) {
802 break;
803 }
804 $result .= $data;
805 } while ( true );
806 pclose( $handle );
807 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
808 return ! $conflict;
809 }
810
811 /**
812 * @todo document
813 */
814 function wfVarDump( $var ) {
815 global $wgOut;
816 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
817 if ( headers_sent() || !@is_object( $wgOut ) ) {
818 print $s;
819 } else {
820 $wgOut->addHTML( $s );
821 }
822 }
823
824 /**
825 * Provide a simple HTTP error.
826 */
827 function wfHttpError( $code, $label, $desc ) {
828 global $wgOut;
829 $wgOut->disable();
830 header( "HTTP/1.0 $code $label" );
831 header( "Status: $code $label" );
832 $wgOut->sendCacheControl();
833
834 header( 'Content-type: text/html' );
835 print "<html><head><title>" .
836 htmlspecialchars( $label ) .
837 "</title></head><body><h1>" .
838 htmlspecialchars( $label ) .
839 "</h1><p>" .
840 htmlspecialchars( $desc ) .
841 "</p></body></html>\n";
842 }
843
844 /**
845 * Converts an Accept-* header into an array mapping string values to quality
846 * factors
847 */
848 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
849 # No arg means accept anything (per HTTP spec)
850 if( !$accept ) {
851 return array( $def => 1 );
852 }
853
854 $prefs = array();
855
856 $parts = explode( ',', $accept );
857
858 foreach( $parts as $part ) {
859 # FIXME: doesn't deal with params like 'text/html; level=1'
860 @list( $value, $qpart ) = explode( ';', $part );
861 if( !isset( $qpart ) ) {
862 $prefs[$value] = 1;
863 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
864 $prefs[$value] = $match[1];
865 }
866 }
867
868 return $prefs;
869 }
870
871 /**
872 * Checks if a given MIME type matches any of the keys in the given
873 * array. Basic wildcards are accepted in the array keys.
874 *
875 * Returns the matching MIME type (or wildcard) if a match, otherwise
876 * NULL if no match.
877 *
878 * @param string $type
879 * @param array $avail
880 * @return string
881 * @access private
882 */
883 function mimeTypeMatch( $type, $avail ) {
884 if( array_key_exists($type, $avail) ) {
885 return $type;
886 } else {
887 $parts = explode( '/', $type );
888 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
889 return $parts[0] . '/*';
890 } elseif( array_key_exists( '*/*', $avail ) ) {
891 return '*/*';
892 } else {
893 return NULL;
894 }
895 }
896 }
897
898 /**
899 * Returns the 'best' match between a client's requested internet media types
900 * and the server's list of available types. Each list should be an associative
901 * array of type to preference (preference is a float between 0.0 and 1.0).
902 * Wildcards in the types are acceptable.
903 *
904 * @param array $cprefs Client's acceptable type list
905 * @param array $sprefs Server's offered types
906 * @return string
907 *
908 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
909 * XXX: generalize to negotiate other stuff
910 */
911 function wfNegotiateType( $cprefs, $sprefs ) {
912 $combine = array();
913
914 foreach( array_keys($sprefs) as $type ) {
915 $parts = explode( '/', $type );
916 if( $parts[1] != '*' ) {
917 $ckey = mimeTypeMatch( $type, $cprefs );
918 if( $ckey ) {
919 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
920 }
921 }
922 }
923
924 foreach( array_keys( $cprefs ) as $type ) {
925 $parts = explode( '/', $type );
926 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
927 $skey = mimeTypeMatch( $type, $sprefs );
928 if( $skey ) {
929 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
930 }
931 }
932 }
933
934 $bestq = 0;
935 $besttype = NULL;
936
937 foreach( array_keys( $combine ) as $type ) {
938 if( $combine[$type] > $bestq ) {
939 $besttype = $type;
940 $bestq = $combine[$type];
941 }
942 }
943
944 return $besttype;
945 }
946
947 /**
948 * Array lookup
949 * Returns an array where the values in the first array are replaced by the
950 * values in the second array with the corresponding keys
951 *
952 * @return array
953 */
954 function wfArrayLookup( $a, $b ) {
955 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
956 }
957
958 /**
959 * Convenience function; returns MediaWiki timestamp for the present time.
960 * @return string
961 */
962 function wfTimestampNow() {
963 # return NOW
964 return wfTimestamp( TS_MW, time() );
965 }
966
967 /**
968 * Reference-counted warning suppression
969 */
970 function wfSuppressWarnings( $end = false ) {
971 static $suppressCount = 0;
972 static $originalLevel = false;
973
974 if ( $end ) {
975 if ( $suppressCount ) {
976 $suppressCount --;
977 if ( !$suppressCount ) {
978 error_reporting( $originalLevel );
979 }
980 }
981 } else {
982 if ( !$suppressCount ) {
983 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
984 }
985 $suppressCount++;
986 }
987 }
988
989 /**
990 * Restore error level to previous value
991 */
992 function wfRestoreWarnings() {
993 wfSuppressWarnings( true );
994 }
995
996 # Autodetect, convert and provide timestamps of various types
997
998 /**
999 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1000 */
1001 define('TS_UNIX', 0);
1002
1003 /**
1004 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1005 */
1006 define('TS_MW', 1);
1007
1008 /**
1009 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1010 */
1011 define('TS_DB', 2);
1012
1013 /**
1014 * RFC 2822 format, for E-mail and HTTP headers
1015 */
1016 define('TS_RFC2822', 3);
1017
1018 /**
1019 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1020 *
1021 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1022 * DateTime tag and page 36 for the DateTimeOriginal and
1023 * DateTimeDigitized tags.
1024 */
1025 define('TS_EXIF', 4);
1026
1027
1028 /**
1029 * @param mixed $outputtype A timestamp in one of the supported formats, the
1030 * function will autodetect which format is supplied
1031 and act accordingly.
1032 * @return string Time in the format specified in $outputtype
1033 */
1034 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1035 if ($ts==0) {
1036 $uts=time();
1037 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1038 # TS_DB
1039 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1040 (int)$da[2],(int)$da[3],(int)$da[1]);
1041 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1042 # TS_EXIF
1043 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1044 (int)$da[2],(int)$da[3],(int)$da[1]);
1045 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1046 # TS_MW
1047 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1048 (int)$da[2],(int)$da[3],(int)$da[1]);
1049 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1050 # TS_UNIX
1051 $uts=$ts;
1052 } else {
1053 # Bogus value; fall back to the epoch...
1054 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1055 $uts = 0;
1056 }
1057
1058
1059 switch($outputtype) {
1060 case TS_UNIX:
1061 return $uts;
1062 case TS_MW:
1063 return gmdate( 'YmdHis', $uts );
1064 case TS_DB:
1065 return gmdate( 'Y-m-d H:i:s', $uts );
1066 // This shouldn't ever be used, but is included for completeness
1067 case TS_EXIF:
1068 return gmdate( 'Y:m:d H:i:s', $uts );
1069 case TS_RFC2822:
1070 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1071 default:
1072 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1073 }
1074 }
1075
1076 /**
1077 * Return a formatted timestamp, or null if input is null.
1078 * For dealing with nullable timestamp columns in the database.
1079 * @param int $outputtype
1080 * @param string $ts
1081 * @return string
1082 */
1083 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1084 if( is_null( $ts ) ) {
1085 return null;
1086 } else {
1087 return wfTimestamp( $outputtype, $ts );
1088 }
1089 }
1090
1091 /**
1092 * Check where as the operating system is Windows
1093 *
1094 * @return bool True if it's windows, False otherwise.
1095 */
1096 function wfIsWindows() {
1097 if (substr(php_uname(), 0, 7) == 'Windows') {
1098 return true;
1099 } else {
1100 return false;
1101 }
1102 }
1103
1104 /**
1105 * Swap two variables
1106 */
1107 function swap( &$x, &$y ) {
1108 $z = $x;
1109 $x = $y;
1110 $y = $z;
1111 }
1112
1113 function wfGetSiteNotice() {
1114 global $wgSiteNotice, $wgTitle, $wgOut;
1115 $fname = 'wfGetSiteNotice';
1116 wfProfileIn( $fname );
1117
1118 $notice = wfMsg( 'sitenotice' );
1119 if($notice == '&lt;sitenotice&gt;') $notice = '';
1120 # Allow individual wikis to turn it off
1121 if ( $notice == '-' ) {
1122 $notice = '';
1123 } else {
1124 if ($notice == '') {
1125 $notice = $wgSiteNotice;
1126 }
1127 if($notice != '-' && $notice != '') {
1128 $specialparser = new Parser();
1129 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1130 $notice = $parserOutput->getText();
1131 }
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 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 ?>