* Add ability to break off certain debug topics into additional log files;
[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 return false;
812 }
813
814 # Make temporary files
815 $td = wfTempDir();
816 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
817 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
818 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
819
820 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
821 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
822 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
823
824 # Check for a conflict
825 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
826 wfEscapeShellArg( $mytextName ) . ' ' .
827 wfEscapeShellArg( $oldtextName ) . ' ' .
828 wfEscapeShellArg( $yourtextName );
829 $handle = popen( $cmd, 'r' );
830
831 if( fgets( $handle, 1024 ) ){
832 $conflict = true;
833 } else {
834 $conflict = false;
835 }
836 pclose( $handle );
837
838 # Merge differences
839 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
840 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
841 $handle = popen( $cmd, 'r' );
842 $result = '';
843 do {
844 $data = fread( $handle, 8192 );
845 if ( strlen( $data ) == 0 ) {
846 break;
847 }
848 $result .= $data;
849 } while ( true );
850 pclose( $handle );
851 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
852 return ! $conflict;
853 }
854
855 /**
856 * @todo document
857 */
858 function wfVarDump( $var ) {
859 global $wgOut;
860 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
861 if ( headers_sent() || !@is_object( $wgOut ) ) {
862 print $s;
863 } else {
864 $wgOut->addHTML( $s );
865 }
866 }
867
868 /**
869 * Provide a simple HTTP error.
870 */
871 function wfHttpError( $code, $label, $desc ) {
872 global $wgOut;
873 $wgOut->disable();
874 header( "HTTP/1.0 $code $label" );
875 header( "Status: $code $label" );
876 $wgOut->sendCacheControl();
877
878 header( 'Content-type: text/html' );
879 print "<html><head><title>" .
880 htmlspecialchars( $label ) .
881 "</title></head><body><h1>" .
882 htmlspecialchars( $label ) .
883 "</h1><p>" .
884 htmlspecialchars( $desc ) .
885 "</p></body></html>\n";
886 }
887
888 /**
889 * Converts an Accept-* header into an array mapping string values to quality
890 * factors
891 */
892 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
893 # No arg means accept anything (per HTTP spec)
894 if( !$accept ) {
895 return array( $def => 1 );
896 }
897
898 $prefs = array();
899
900 $parts = explode( ',', $accept );
901
902 foreach( $parts as $part ) {
903 # FIXME: doesn't deal with params like 'text/html; level=1'
904 @list( $value, $qpart ) = explode( ';', $part );
905 if( !isset( $qpart ) ) {
906 $prefs[$value] = 1;
907 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
908 $prefs[$value] = $match[1];
909 }
910 }
911
912 return $prefs;
913 }
914
915 /**
916 * Checks if a given MIME type matches any of the keys in the given
917 * array. Basic wildcards are accepted in the array keys.
918 *
919 * Returns the matching MIME type (or wildcard) if a match, otherwise
920 * NULL if no match.
921 *
922 * @param string $type
923 * @param array $avail
924 * @return string
925 * @access private
926 */
927 function mimeTypeMatch( $type, $avail ) {
928 if( array_key_exists($type, $avail) ) {
929 return $type;
930 } else {
931 $parts = explode( '/', $type );
932 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
933 return $parts[0] . '/*';
934 } elseif( array_key_exists( '*/*', $avail ) ) {
935 return '*/*';
936 } else {
937 return NULL;
938 }
939 }
940 }
941
942 /**
943 * Returns the 'best' match between a client's requested internet media types
944 * and the server's list of available types. Each list should be an associative
945 * array of type to preference (preference is a float between 0.0 and 1.0).
946 * Wildcards in the types are acceptable.
947 *
948 * @param array $cprefs Client's acceptable type list
949 * @param array $sprefs Server's offered types
950 * @return string
951 *
952 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
953 * XXX: generalize to negotiate other stuff
954 */
955 function wfNegotiateType( $cprefs, $sprefs ) {
956 $combine = array();
957
958 foreach( array_keys($sprefs) as $type ) {
959 $parts = explode( '/', $type );
960 if( $parts[1] != '*' ) {
961 $ckey = mimeTypeMatch( $type, $cprefs );
962 if( $ckey ) {
963 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
964 }
965 }
966 }
967
968 foreach( array_keys( $cprefs ) as $type ) {
969 $parts = explode( '/', $type );
970 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
971 $skey = mimeTypeMatch( $type, $sprefs );
972 if( $skey ) {
973 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
974 }
975 }
976 }
977
978 $bestq = 0;
979 $besttype = NULL;
980
981 foreach( array_keys( $combine ) as $type ) {
982 if( $combine[$type] > $bestq ) {
983 $besttype = $type;
984 $bestq = $combine[$type];
985 }
986 }
987
988 return $besttype;
989 }
990
991 /**
992 * Array lookup
993 * Returns an array where the values in the first array are replaced by the
994 * values in the second array with the corresponding keys
995 *
996 * @return array
997 */
998 function wfArrayLookup( $a, $b ) {
999 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1000 }
1001
1002 /**
1003 * Convenience function; returns MediaWiki timestamp for the present time.
1004 * @return string
1005 */
1006 function wfTimestampNow() {
1007 # return NOW
1008 return wfTimestamp( TS_MW, time() );
1009 }
1010
1011 /**
1012 * Reference-counted warning suppression
1013 */
1014 function wfSuppressWarnings( $end = false ) {
1015 static $suppressCount = 0;
1016 static $originalLevel = false;
1017
1018 if ( $end ) {
1019 if ( $suppressCount ) {
1020 $suppressCount --;
1021 if ( !$suppressCount ) {
1022 error_reporting( $originalLevel );
1023 }
1024 }
1025 } else {
1026 if ( !$suppressCount ) {
1027 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1028 }
1029 $suppressCount++;
1030 }
1031 }
1032
1033 /**
1034 * Restore error level to previous value
1035 */
1036 function wfRestoreWarnings() {
1037 wfSuppressWarnings( true );
1038 }
1039
1040 # Autodetect, convert and provide timestamps of various types
1041
1042 /**
1043 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1044 */
1045 define('TS_UNIX', 0);
1046
1047 /**
1048 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1049 */
1050 define('TS_MW', 1);
1051
1052 /**
1053 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1054 */
1055 define('TS_DB', 2);
1056
1057 /**
1058 * RFC 2822 format, for E-mail and HTTP headers
1059 */
1060 define('TS_RFC2822', 3);
1061
1062 /**
1063 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1064 *
1065 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1066 * DateTime tag and page 36 for the DateTimeOriginal and
1067 * DateTimeDigitized tags.
1068 */
1069 define('TS_EXIF', 4);
1070
1071 /**
1072 * Oracle format time.
1073 */
1074 define('TS_ORACLE', 5);
1075
1076 /**
1077 * @param mixed $outputtype A timestamp in one of the supported formats, the
1078 * function will autodetect which format is supplied
1079 and act accordingly.
1080 * @return string Time in the format specified in $outputtype
1081 */
1082 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1083 wfdebug("ts: $ts\n");
1084 if ($ts==0) {
1085 $uts=time();
1086 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1087 # TS_DB
1088 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1089 (int)$da[2],(int)$da[3],(int)$da[1]);
1090 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1091 # TS_EXIF
1092 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1093 (int)$da[2],(int)$da[3],(int)$da[1]);
1094 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1095 # TS_MW
1096 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1097 (int)$da[2],(int)$da[3],(int)$da[1]);
1098 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1099 # TS_UNIX
1100 $uts=$ts;
1101 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1102 # TS_ORACLE
1103 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1104 str_replace("+00:00", "UTC", $ts)));
1105 } else {
1106 # Bogus value; fall back to the epoch...
1107 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1108 $uts = 0;
1109 }
1110
1111
1112 switch($outputtype) {
1113 case TS_UNIX:
1114 return $uts;
1115 case TS_MW:
1116 return gmdate( 'YmdHis', $uts );
1117 case TS_DB:
1118 return gmdate( 'Y-m-d H:i:s', $uts );
1119 // This shouldn't ever be used, but is included for completeness
1120 case TS_EXIF:
1121 return gmdate( 'Y:m:d H:i:s', $uts );
1122 case TS_RFC2822:
1123 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1124 case TS_ORACLE:
1125 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1126 default:
1127 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1128 }
1129 }
1130
1131 /**
1132 * Return a formatted timestamp, or null if input is null.
1133 * For dealing with nullable timestamp columns in the database.
1134 * @param int $outputtype
1135 * @param string $ts
1136 * @return string
1137 */
1138 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1139 if( is_null( $ts ) ) {
1140 return null;
1141 } else {
1142 return wfTimestamp( $outputtype, $ts );
1143 }
1144 }
1145
1146 /**
1147 * Check where as the operating system is Windows
1148 *
1149 * @return bool True if it's windows, False otherwise.
1150 */
1151 function wfIsWindows() {
1152 if (substr(php_uname(), 0, 7) == 'Windows') {
1153 return true;
1154 } else {
1155 return false;
1156 }
1157 }
1158
1159 /**
1160 * Swap two variables
1161 */
1162 function swap( &$x, &$y ) {
1163 $z = $x;
1164 $x = $y;
1165 $y = $z;
1166 }
1167
1168 function wfGetSiteNotice() {
1169 global $wgSiteNotice, $wgTitle, $wgOut;
1170 $fname = 'wfGetSiteNotice';
1171 wfProfileIn( $fname );
1172
1173 $notice = wfMsg( 'sitenotice' );
1174 if( $notice == '&lt;sitenotice&gt;' || $notice == '-' ) {
1175 $notice = '';
1176 }
1177 if( $notice == '' ) {
1178 # We may also need to override a message with eg downtime info
1179 # FIXME: make this work!
1180 $notice = $wgSiteNotice;
1181 }
1182 if($notice != '-' && $notice != '') {
1183 $specialparser = new Parser();
1184 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1185 $notice = $parserOutput->getText();
1186 }
1187 wfProfileOut( $fname );
1188 return $notice;
1189 }
1190
1191 /**
1192 * Format an XML element with given attributes and, optionally, text content.
1193 * Element and attribute names are assumed to be ready for literal inclusion.
1194 * Strings are assumed to not contain XML-illegal characters; special
1195 * characters (<, >, &) are escaped but illegals are not touched.
1196 *
1197 * @param string $element
1198 * @param array $attribs Name=>value pairs. Values will be escaped.
1199 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1200 * @return string
1201 */
1202 function wfElement( $element, $attribs = null, $contents = '') {
1203 $out = '<' . $element;
1204 if( !is_null( $attribs ) ) {
1205 foreach( $attribs as $name => $val ) {
1206 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1207 }
1208 }
1209 if( is_null( $contents ) ) {
1210 $out .= '>';
1211 } else {
1212 if( $contents == '' ) {
1213 $out .= ' />';
1214 } else {
1215 $out .= '>';
1216 $out .= htmlspecialchars( $contents );
1217 $out .= "</$element>";
1218 }
1219 }
1220 return $out;
1221 }
1222
1223 /**
1224 * Format an XML element as with wfElement(), but run text through the
1225 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1226 * is passed.
1227 *
1228 * @param string $element
1229 * @param array $attribs Name=>value pairs. Values will be escaped.
1230 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1231 * @return string
1232 */
1233 function wfElementClean( $element, $attribs = array(), $contents = '') {
1234 if( $attribs ) {
1235 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1236 }
1237 if( $contents ) {
1238 $contents = UtfNormal::cleanUp( $contents );
1239 }
1240 return wfElement( $element, $attribs, $contents );
1241 }
1242
1243 /**
1244 * Create a namespace selector
1245 *
1246 * @param mixed $selected The namespace which should be selected, default ''
1247 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1248 * @return Html string containing the namespace selector
1249 */
1250 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1251 global $wgContLang;
1252 $s = "<select name='namespace' class='namespaceselector'>\n";
1253 $arr = $wgContLang->getFormattedNamespaces();
1254 if( !is_null($allnamespaces) ) {
1255 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) + $arr;
1256 }
1257 foreach ($arr as $index => $name) {
1258 if ($index < NS_MAIN) continue;
1259
1260 $name = $index !== 0 ? $name : wfMsgHtml('blanknamespace');
1261
1262 if ($index === $selected) {
1263 $s .= wfElement("option",
1264 array("value" => $index, "selected" => "selected"),
1265 $name);
1266 } else {
1267 $s .= wfElement("option", array("value" => $index), $name);
1268 }
1269 }
1270 $s .= "</select>\n";
1271 return $s;
1272 }
1273
1274 /** Global singleton instance of MimeMagic. This is initialized on demand,
1275 * please always use the wfGetMimeMagic() function to get the instance.
1276 *
1277 * @private
1278 */
1279 $wgMimeMagic= NULL;
1280
1281 /** Factory functions for the global MimeMagic object.
1282 * This function always returns the same singleton instance of MimeMagic.
1283 * That objects will be instantiated on the first call to this function.
1284 * If needed, the MimeMagic.php file is automatically included by this function.
1285 * @return MimeMagic the global MimeMagic objects.
1286 */
1287 function &wfGetMimeMagic() {
1288 global $wgMimeMagic;
1289
1290 if (!is_null($wgMimeMagic)) {
1291 return $wgMimeMagic;
1292 }
1293
1294 if (!class_exists("MimeMagic")) {
1295 #include on demand
1296 require_once("MimeMagic.php");
1297 }
1298
1299 $wgMimeMagic= new MimeMagic();
1300
1301 return $wgMimeMagic;
1302 }
1303
1304
1305 /**
1306 * Tries to get the system directory for temporary files.
1307 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1308 * and if none are set /tmp is returned as the generic Unix default.
1309 *
1310 * NOTE: When possible, use the tempfile() function to create temporary
1311 * files to avoid race conditions on file creation, etc.
1312 *
1313 * @return string
1314 */
1315 function wfTempDir() {
1316 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1317 $tmp = getenv( $var );
1318 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1319 return $tmp;
1320 }
1321 }
1322 # Hope this is Unix of some kind!
1323 return '/tmp';
1324 }
1325
1326 /**
1327 * Make directory, and make all parent directories if they don't exist
1328 */
1329 function wfMkdirParents( $fullDir, $mode ) {
1330 $parts = explode( '/', $fullDir );
1331 $path = '';
1332 $success = false;
1333 foreach ( $parts as $dir ) {
1334 $path .= $dir . '/';
1335 if ( !is_dir( $path ) ) {
1336 if ( !mkdir( $path, $mode ) ) {
1337 return false;
1338 }
1339 }
1340 }
1341 return true;
1342 }
1343
1344 /**
1345 * Increment a statistics counter
1346 */
1347 function wfIncrStats( $key ) {
1348 global $wgDBname, $wgMemc;
1349 $key = "$wgDBname:stats:$key";
1350 if ( is_null( $wgMemc->incr( $key ) ) ) {
1351 $wgMemc->add( $key, 1 );
1352 }
1353 }
1354
1355 /**
1356 * @param mixed $nr The number to format
1357 * @param int $acc The number of digits after the decimal point, default 2
1358 * @param bool $round Whether or not to round the value, default true
1359 * @return float
1360 */
1361 function wfPercent( $nr, $acc = 2, $round = true ) {
1362 $ret = sprintf( "%.${acc}f", $nr );
1363 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1364 }
1365
1366 /**
1367 * Encrypt a username/password.
1368 *
1369 * @param string $userid ID of the user
1370 * @param string $password Password of the user
1371 * @return string Hashed password
1372 */
1373 function wfEncryptPassword( $userid, $password ) {
1374 global $wgPasswordSalt;
1375 $p = md5( $password);
1376
1377 if($wgPasswordSalt)
1378 return md5( "{$userid}-{$p}" );
1379 else
1380 return $p;
1381 }
1382
1383 /**
1384 * Appends to second array if $value differs from that in $default
1385 */
1386 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1387 if ( is_null( $changed ) ) {
1388 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1389 }
1390 if ( $default[$key] !== $value ) {
1391 $changed[$key] = $value;
1392 }
1393 }
1394
1395 /**
1396 * Since wfMsg() and co suck, they don't return false if the message key they
1397 * looked up didn't exist but a XHTML string, this function checks for the
1398 * nonexistance of messages by looking at wfMsg() output
1399 *
1400 * @param $msg The message key looked up
1401 * @param $wfMsgOut The output of wfMsg*()
1402 * @return bool
1403 */
1404 function wfNoMsg( $msg, $wfMsgOut ) {
1405 return $wfMsgOut === "&lt;$msg&gt;";
1406 }
1407 ?>