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