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