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