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