* Simple rate limiter for edits and page moves; set $wgRateLimits
[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 # Replace arguments
426 if( count( $args ) ) {
427 $message = str_replace( $replacementKeys, $args, $message );
428 }
429 wfProfileOut( $fname );
430 return $message;
431 }
432
433
434
435 /**
436 * Just like exit() but makes a note of it.
437 * Commits open transactions except if the error parameter is set
438 */
439 function wfAbruptExit( $error = false ){
440 global $wgLoadBalancer;
441 static $called = false;
442 if ( $called ){
443 exit();
444 }
445 $called = true;
446
447 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
448 $bt = debug_backtrace();
449 for($i = 0; $i < count($bt) ; $i++){
450 $file = $bt[$i]['file'];
451 $line = $bt[$i]['line'];
452 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
453 }
454 } else {
455 wfDebug('WARNING: Abrupt exit\n');
456 }
457 if ( !$error ) {
458 $wgLoadBalancer->closeAll();
459 }
460 exit();
461 }
462
463 /**
464 * @todo document
465 */
466 function wfErrorExit() {
467 wfAbruptExit( true );
468 }
469
470 /**
471 * Die with a backtrace
472 * This is meant as a debugging aid to track down where bad data comes from.
473 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
474 *
475 * @param string $msg Message shown when dieing.
476 */
477 function wfDebugDieBacktrace( $msg = '' ) {
478 global $wgCommandLineMode;
479
480 $backtrace = wfBacktrace();
481 if ( $backtrace !== false ) {
482 if ( $wgCommandLineMode ) {
483 $msg .= "\nBacktrace:\n$backtrace";
484 } else {
485 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
486 }
487 }
488 die( $msg );
489 }
490
491 function wfBacktrace() {
492 global $wgCommandLineMode;
493 if ( !function_exists( 'debug_backtrace' ) ) {
494 return false;
495 }
496
497 if ( $wgCommandLineMode ) {
498 $msg = '';
499 } else {
500 $msg = "<ul>\n";
501 }
502 $backtrace = debug_backtrace();
503 foreach( $backtrace as $call ) {
504 if( isset( $call['file'] ) ) {
505 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
506 $file = $f[count($f)-1];
507 } else {
508 $file = '-';
509 }
510 if( isset( $call['line'] ) ) {
511 $line = $call['line'];
512 } else {
513 $line = '-';
514 }
515 if ( $wgCommandLineMode ) {
516 $msg .= "$file line $line calls ";
517 } else {
518 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
519 }
520 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
521 $msg .= $call['function'] . '()';
522
523 if ( $wgCommandLineMode ) {
524 $msg .= "\n";
525 } else {
526 $msg .= "</li>\n";
527 }
528 }
529 if ( $wgCommandLineMode ) {
530 $msg .= "\n";
531 } else {
532 $msg .= "</ul>\n";
533 }
534
535 return $msg;
536 }
537
538
539 /* Some generic result counters, pulled out of SearchEngine */
540
541
542 /**
543 * @todo document
544 */
545 function wfShowingResults( $offset, $limit ) {
546 global $wgLang;
547 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
548 }
549
550 /**
551 * @todo document
552 */
553 function wfShowingResultsNum( $offset, $limit, $num ) {
554 global $wgLang;
555 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
556 }
557
558 /**
559 * @todo document
560 */
561 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
562 global $wgUser, $wgLang;
563 $fmtLimit = $wgLang->formatNum( $limit );
564 $prev = wfMsg( 'prevn', $fmtLimit );
565 $next = wfMsg( 'nextn', $fmtLimit );
566
567 if( is_object( $link ) ) {
568 $title =& $link;
569 } else {
570 $title =& Title::newFromText( $link );
571 if( is_null( $title ) ) {
572 return false;
573 }
574 }
575
576 $sk = $wgUser->getSkin();
577 if ( 0 != $offset ) {
578 $po = $offset - $limit;
579 if ( $po < 0 ) { $po = 0; }
580 $q = "limit={$limit}&offset={$po}";
581 if ( '' != $query ) { $q .= '&'.$query; }
582 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
583 } else { $plink = $prev; }
584
585 $no = $offset + $limit;
586 $q = 'limit='.$limit.'&offset='.$no;
587 if ( '' != $query ) { $q .= '&'.$query; }
588
589 if ( $atend ) {
590 $nlink = $next;
591 } else {
592 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
593 }
594 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
595 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
596 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
597 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
598 wfNumLink( $offset, 500, $title, $query );
599
600 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
601 }
602
603 /**
604 * @todo document
605 */
606 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
607 global $wgUser, $wgLang;
608 if ( '' == $query ) { $q = ''; }
609 else { $q = $query.'&'; }
610 $q .= 'limit='.$limit.'&offset='.$offset;
611
612 $fmtLimit = $wgLang->formatNum( $limit );
613 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
614 return $s;
615 }
616
617 /**
618 * @todo document
619 * @todo FIXME: we may want to blacklist some broken browsers
620 *
621 * @return bool Whereas client accept gzip compression
622 */
623 function wfClientAcceptsGzip() {
624 global $wgUseGzip;
625 if( $wgUseGzip ) {
626 # FIXME: we may want to blacklist some broken browsers
627 if( preg_match(
628 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
629 $_SERVER['HTTP_ACCEPT_ENCODING'],
630 $m ) ) {
631 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
632 wfDebug( " accepts gzip\n" );
633 return true;
634 }
635 }
636 return false;
637 }
638
639 /**
640 * Yay, more global functions!
641 */
642 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
643 global $wgRequest;
644 return $wgRequest->getLimitOffset( $deflimit, $optionname );
645 }
646
647 /**
648 * Escapes the given text so that it may be output using addWikiText()
649 * without any linking, formatting, etc. making its way through. This
650 * is achieved by substituting certain characters with HTML entities.
651 * As required by the callers, <nowiki> is not used. It currently does
652 * not filter out characters which have special meaning only at the
653 * start of a line, such as "*".
654 *
655 * @param string $text Text to be escaped
656 */
657 function wfEscapeWikiText( $text ) {
658 $text = str_replace(
659 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
660 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
661 htmlspecialchars($text) );
662 return $text;
663 }
664
665 /**
666 * @todo document
667 */
668 function wfQuotedPrintable( $string, $charset = '' ) {
669 # Probably incomplete; see RFC 2045
670 if( empty( $charset ) ) {
671 global $wgInputEncoding;
672 $charset = $wgInputEncoding;
673 }
674 $charset = strtoupper( $charset );
675 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
676
677 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
678 $replace = $illegal . '\t ?_';
679 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
680 $out = "=?$charset?Q?";
681 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
682 $out .= '?=';
683 return $out;
684 }
685
686 /**
687 * Returns an escaped string suitable for inclusion in a string literal
688 * for JavaScript source code.
689 * Illegal control characters are assumed not to be present.
690 *
691 * @param string $string
692 * @return string
693 */
694 function wfEscapeJsString( $string ) {
695 // See ECMA 262 section 7.8.4 for string literal format
696 $pairs = array(
697 "\\" => "\\\\",
698 "\"" => "\\\"",
699 "\'" => "\\\'",
700 "\n" => "\\n",
701 "\r" => "\\r",
702
703 # To avoid closing the element or CDATA section
704 "<" => "\\x3c",
705 ">" => "\\x3e",
706 );
707 return strtr( $string, $pairs );
708 }
709
710 /**
711 * @todo document
712 * @return float
713 */
714 function wfTime() {
715 $st = explode( ' ', microtime() );
716 return (float)$st[0] + (float)$st[1];
717 }
718
719 /**
720 * Changes the first character to an HTML entity
721 */
722 function wfHtmlEscapeFirst( $text ) {
723 $ord = ord($text);
724 $newText = substr($text, 1);
725 return "&#$ord;$newText";
726 }
727
728 /**
729 * Sets dest to source and returns the original value of dest
730 * If source is NULL, it just returns the value, it doesn't set the variable
731 */
732 function wfSetVar( &$dest, $source ) {
733 $temp = $dest;
734 if ( !is_null( $source ) ) {
735 $dest = $source;
736 }
737 return $temp;
738 }
739
740 /**
741 * As for wfSetVar except setting a bit
742 */
743 function wfSetBit( &$dest, $bit, $state = true ) {
744 $temp = (bool)($dest & $bit );
745 if ( !is_null( $state ) ) {
746 if ( $state ) {
747 $dest |= $bit;
748 } else {
749 $dest &= ~$bit;
750 }
751 }
752 return $temp;
753 }
754
755 /**
756 * This function takes two arrays as input, and returns a CGI-style string, e.g.
757 * "days=7&limit=100". Options in the first array override options in the second.
758 * Options set to "" will not be output.
759 */
760 function wfArrayToCGI( $array1, $array2 = NULL )
761 {
762 if ( !is_null( $array2 ) ) {
763 $array1 = $array1 + $array2;
764 }
765
766 $cgi = '';
767 foreach ( $array1 as $key => $value ) {
768 if ( '' !== $value ) {
769 if ( '' != $cgi ) {
770 $cgi .= '&';
771 }
772 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
773 }
774 }
775 return $cgi;
776 }
777
778 /**
779 * This is obsolete, use SquidUpdate::purge()
780 * @deprecated
781 */
782 function wfPurgeSquidServers ($urlArr) {
783 SquidUpdate::purge( $urlArr );
784 }
785
786 /**
787 * Windows-compatible version of escapeshellarg()
788 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
789 * function puts single quotes in regardless of OS
790 */
791 function wfEscapeShellArg( ) {
792 $args = func_get_args();
793 $first = true;
794 $retVal = '';
795 foreach ( $args as $arg ) {
796 if ( !$first ) {
797 $retVal .= ' ';
798 } else {
799 $first = false;
800 }
801
802 if ( wfIsWindows() ) {
803 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
804 } else {
805 $retVal .= escapeshellarg( $arg );
806 }
807 }
808 return $retVal;
809 }
810
811 /**
812 * wfMerge attempts to merge differences between three texts.
813 * Returns true for a clean merge and false for failure or a conflict.
814 */
815 function wfMerge( $old, $mine, $yours, &$result ){
816 global $wgDiff3;
817
818 # This check may also protect against code injection in
819 # case of broken installations.
820 if(! file_exists( $wgDiff3 ) ){
821 return false;
822 }
823
824 # Make temporary files
825 $td = wfTempDir();
826 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
827 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
828 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
829
830 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
831 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
832 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
833
834 # Check for a conflict
835 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
836 wfEscapeShellArg( $mytextName ) . ' ' .
837 wfEscapeShellArg( $oldtextName ) . ' ' .
838 wfEscapeShellArg( $yourtextName );
839 $handle = popen( $cmd, 'r' );
840
841 if( fgets( $handle, 1024 ) ){
842 $conflict = true;
843 } else {
844 $conflict = false;
845 }
846 pclose( $handle );
847
848 # Merge differences
849 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
850 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
851 $handle = popen( $cmd, 'r' );
852 $result = '';
853 do {
854 $data = fread( $handle, 8192 );
855 if ( strlen( $data ) == 0 ) {
856 break;
857 }
858 $result .= $data;
859 } while ( true );
860 pclose( $handle );
861 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
862 return ! $conflict;
863 }
864
865 /**
866 * @todo document
867 */
868 function wfVarDump( $var ) {
869 global $wgOut;
870 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
871 if ( headers_sent() || !@is_object( $wgOut ) ) {
872 print $s;
873 } else {
874 $wgOut->addHTML( $s );
875 }
876 }
877
878 /**
879 * Provide a simple HTTP error.
880 */
881 function wfHttpError( $code, $label, $desc ) {
882 global $wgOut;
883 $wgOut->disable();
884 header( "HTTP/1.0 $code $label" );
885 header( "Status: $code $label" );
886 $wgOut->sendCacheControl();
887
888 header( 'Content-type: text/html' );
889 print "<html><head><title>" .
890 htmlspecialchars( $label ) .
891 "</title></head><body><h1>" .
892 htmlspecialchars( $label ) .
893 "</h1><p>" .
894 htmlspecialchars( $desc ) .
895 "</p></body></html>\n";
896 }
897
898 /**
899 * Converts an Accept-* header into an array mapping string values to quality
900 * factors
901 */
902 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
903 # No arg means accept anything (per HTTP spec)
904 if( !$accept ) {
905 return array( $def => 1 );
906 }
907
908 $prefs = array();
909
910 $parts = explode( ',', $accept );
911
912 foreach( $parts as $part ) {
913 # FIXME: doesn't deal with params like 'text/html; level=1'
914 @list( $value, $qpart ) = explode( ';', $part );
915 if( !isset( $qpart ) ) {
916 $prefs[$value] = 1;
917 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
918 $prefs[$value] = $match[1];
919 }
920 }
921
922 return $prefs;
923 }
924
925 /**
926 * Checks if a given MIME type matches any of the keys in the given
927 * array. Basic wildcards are accepted in the array keys.
928 *
929 * Returns the matching MIME type (or wildcard) if a match, otherwise
930 * NULL if no match.
931 *
932 * @param string $type
933 * @param array $avail
934 * @return string
935 * @access private
936 */
937 function mimeTypeMatch( $type, $avail ) {
938 if( array_key_exists($type, $avail) ) {
939 return $type;
940 } else {
941 $parts = explode( '/', $type );
942 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
943 return $parts[0] . '/*';
944 } elseif( array_key_exists( '*/*', $avail ) ) {
945 return '*/*';
946 } else {
947 return NULL;
948 }
949 }
950 }
951
952 /**
953 * Returns the 'best' match between a client's requested internet media types
954 * and the server's list of available types. Each list should be an associative
955 * array of type to preference (preference is a float between 0.0 and 1.0).
956 * Wildcards in the types are acceptable.
957 *
958 * @param array $cprefs Client's acceptable type list
959 * @param array $sprefs Server's offered types
960 * @return string
961 *
962 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
963 * XXX: generalize to negotiate other stuff
964 */
965 function wfNegotiateType( $cprefs, $sprefs ) {
966 $combine = array();
967
968 foreach( array_keys($sprefs) as $type ) {
969 $parts = explode( '/', $type );
970 if( $parts[1] != '*' ) {
971 $ckey = mimeTypeMatch( $type, $cprefs );
972 if( $ckey ) {
973 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
974 }
975 }
976 }
977
978 foreach( array_keys( $cprefs ) as $type ) {
979 $parts = explode( '/', $type );
980 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
981 $skey = mimeTypeMatch( $type, $sprefs );
982 if( $skey ) {
983 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
984 }
985 }
986 }
987
988 $bestq = 0;
989 $besttype = NULL;
990
991 foreach( array_keys( $combine ) as $type ) {
992 if( $combine[$type] > $bestq ) {
993 $besttype = $type;
994 $bestq = $combine[$type];
995 }
996 }
997
998 return $besttype;
999 }
1000
1001 /**
1002 * Array lookup
1003 * Returns an array where the values in the first array are replaced by the
1004 * values in the second array with the corresponding keys
1005 *
1006 * @return array
1007 */
1008 function wfArrayLookup( $a, $b ) {
1009 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1010 }
1011
1012 /**
1013 * Convenience function; returns MediaWiki timestamp for the present time.
1014 * @return string
1015 */
1016 function wfTimestampNow() {
1017 # return NOW
1018 return wfTimestamp( TS_MW, time() );
1019 }
1020
1021 /**
1022 * Reference-counted warning suppression
1023 */
1024 function wfSuppressWarnings( $end = false ) {
1025 static $suppressCount = 0;
1026 static $originalLevel = false;
1027
1028 if ( $end ) {
1029 if ( $suppressCount ) {
1030 $suppressCount --;
1031 if ( !$suppressCount ) {
1032 error_reporting( $originalLevel );
1033 }
1034 }
1035 } else {
1036 if ( !$suppressCount ) {
1037 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1038 }
1039 $suppressCount++;
1040 }
1041 }
1042
1043 /**
1044 * Restore error level to previous value
1045 */
1046 function wfRestoreWarnings() {
1047 wfSuppressWarnings( true );
1048 }
1049
1050 # Autodetect, convert and provide timestamps of various types
1051
1052 /**
1053 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1054 */
1055 define('TS_UNIX', 0);
1056
1057 /**
1058 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1059 */
1060 define('TS_MW', 1);
1061
1062 /**
1063 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1064 */
1065 define('TS_DB', 2);
1066
1067 /**
1068 * RFC 2822 format, for E-mail and HTTP headers
1069 */
1070 define('TS_RFC2822', 3);
1071
1072 /**
1073 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1074 *
1075 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1076 * DateTime tag and page 36 for the DateTimeOriginal and
1077 * DateTimeDigitized tags.
1078 */
1079 define('TS_EXIF', 4);
1080
1081
1082 /**
1083 * @param mixed $outputtype A timestamp in one of the supported formats, the
1084 * function will autodetect which format is supplied
1085 and act accordingly.
1086 * @return string Time in the format specified in $outputtype
1087 */
1088 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1089 if ($ts==0) {
1090 $uts=time();
1091 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1092 # TS_DB
1093 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1094 (int)$da[2],(int)$da[3],(int)$da[1]);
1095 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1096 # TS_EXIF
1097 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1098 (int)$da[2],(int)$da[3],(int)$da[1]);
1099 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1100 # TS_MW
1101 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1102 (int)$da[2],(int)$da[3],(int)$da[1]);
1103 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1104 # TS_UNIX
1105 $uts=$ts;
1106 } else {
1107 # Bogus value; fall back to the epoch...
1108 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1109 $uts = 0;
1110 }
1111
1112
1113 switch($outputtype) {
1114 case TS_UNIX:
1115 return $uts;
1116 case TS_MW:
1117 return gmdate( 'YmdHis', $uts );
1118 case TS_DB:
1119 return gmdate( 'Y-m-d H:i:s', $uts );
1120 // This shouldn't ever be used, but is included for completeness
1121 case TS_EXIF:
1122 return gmdate( 'Y:m:d H:i:s', $uts );
1123 case TS_RFC2822:
1124 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1125 default:
1126 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1127 }
1128 }
1129
1130 /**
1131 * Return a formatted timestamp, or null if input is null.
1132 * For dealing with nullable timestamp columns in the database.
1133 * @param int $outputtype
1134 * @param string $ts
1135 * @return string
1136 */
1137 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1138 if( is_null( $ts ) ) {
1139 return null;
1140 } else {
1141 return wfTimestamp( $outputtype, $ts );
1142 }
1143 }
1144
1145 /**
1146 * Check where as the operating system is Windows
1147 *
1148 * @return bool True if it's windows, False otherwise.
1149 */
1150 function wfIsWindows() {
1151 if (substr(php_uname(), 0, 7) == 'Windows') {
1152 return true;
1153 } else {
1154 return false;
1155 }
1156 }
1157
1158 /**
1159 * Swap two variables
1160 */
1161 function swap( &$x, &$y ) {
1162 $z = $x;
1163 $x = $y;
1164 $y = $z;
1165 }
1166
1167 function wfGetSiteNotice() {
1168 global $wgSiteNotice, $wgTitle, $wgOut;
1169 $fname = 'wfGetSiteNotice';
1170 wfProfileIn( $fname );
1171
1172 $notice = wfMsg( 'sitenotice' );
1173 if($notice == '&lt;sitenotice&gt;') $notice = '';
1174 # Allow individual wikis to turn it off
1175 if ( $notice == '-' ) {
1176 $notice = '';
1177 } else {
1178 if ($notice == '') {
1179 $notice = $wgSiteNotice;
1180 }
1181 if($notice != '-' && $notice != '') {
1182 $specialparser = new Parser();
1183 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1184 $notice = $parserOutput->getText();
1185 }
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 bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1200 * @return string
1201 */
1202 function wfElement( $element, $attribs = array(), $contents = '') {
1203 $out = '<' . $element;
1204 foreach( $attribs as $name => $val ) {
1205 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1206 }
1207 if( is_null( $contents ) ) {
1208 $out .= '>';
1209 } else {
1210 if( $contents == '' ) {
1211 $out .= ' />';
1212 } else {
1213 $out .= '>';
1214 $out .= htmlspecialchars( $contents );
1215 $out .= "</$element>";
1216 }
1217 }
1218 return $out;
1219 }
1220
1221 /**
1222 * Format an XML element as with wfElement(), but run text through the
1223 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1224 * is passed.
1225 *
1226 * @param string $element
1227 * @param array $attribs Name=>value pairs. Values will be escaped.
1228 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1229 * @return string
1230 */
1231 function wfElementClean( $element, $attribs = array(), $contents = '') {
1232 if( $attribs ) {
1233 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1234 }
1235 return wfElement( $element, $attribs, UtfNormal::cleanUp( $contents ) );
1236 }
1237
1238 /** Global singleton instance of MimeMagic. This is initialized on demand,
1239 * please always use the wfGetMimeMagic() function to get the instance.
1240 *
1241 * @private
1242 */
1243 $wgMimeMagic= NULL;
1244
1245 /** Factory functions for the global MimeMagic object.
1246 * This function always returns the same singleton instance of MimeMagic.
1247 * That objects will be instantiated on the first call to this function.
1248 * If needed, the MimeMagic.php file is automatically included by this function.
1249 * @return MimeMagic the global MimeMagic objects.
1250 */
1251 function &wfGetMimeMagic() {
1252 global $wgMimeMagic;
1253
1254 if (!is_null($wgMimeMagic)) {
1255 return $wgMimeMagic;
1256 }
1257
1258 if (!class_exists("MimeMagic")) {
1259 #include on demand
1260 require_once("MimeMagic.php");
1261 }
1262
1263 $wgMimeMagic= new MimeMagic();
1264
1265 return $wgMimeMagic;
1266 }
1267
1268
1269 /**
1270 * Tries to get the system directory for temporary files.
1271 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1272 * and if none are set /tmp is returned as the generic Unix default.
1273 *
1274 * NOTE: When possible, use the tempfile() function to create temporary
1275 * files to avoid race conditions on file creation, etc.
1276 *
1277 * @return string
1278 */
1279 function wfTempDir() {
1280 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1281 $tmp = getenv( 'TMPDIR' );
1282 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1283 return $tmp;
1284 }
1285 }
1286 # Hope this is Unix of some kind!
1287 return '/tmp';
1288 }
1289
1290 ?>