* Changed do_html_entity_decode()'s default character set from ISO-8859-1 to
[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() * 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 @error_log( $text, 3, $wgDebugLogFile );
273 }
274 }
275
276 /**
277 * Log for database errors
278 * @param string $text Database error message.
279 */
280 function wfLogDBError( $text ) {
281 global $wgDBerrorLog;
282 if ( $wgDBerrorLog ) {
283 $text = date('D M j G:i:s T Y') . "\t".$text;
284 error_log( $text, 3, $wgDBerrorLog );
285 }
286 }
287
288 /**
289 * @todo document
290 */
291 function logProfilingData() {
292 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
293 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
294 $now = wfTime();
295
296 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
297 $start = (float)$sec + (float)$usec;
298 $elapsed = $now - $start;
299 if ( $wgProfiling ) {
300 $prof = wfGetProfilingOutput( $start, $elapsed );
301 $forward = '';
302 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
303 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
304 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
305 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
306 if( !empty( $_SERVER['HTTP_FROM'] ) )
307 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
308 if( $forward )
309 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
310 if( $wgUser->isAnon() )
311 $forward .= ' anon';
312 $log = sprintf( "%s\t%04.3f\t%s\n",
313 gmdate( 'YmdHis' ), $elapsed,
314 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
315 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
316 error_log( $log . $prof, 3, $wgDebugLogFile );
317 }
318 }
319 }
320
321 /**
322 * Check if the wiki read-only lock file is present. This can be used to lock
323 * off editing functions, but doesn't guarantee that the database will not be
324 * modified.
325 * @return bool
326 */
327 function wfReadOnly() {
328 global $wgReadOnlyFile;
329
330 if ( '' == $wgReadOnlyFile ) {
331 return false;
332 }
333 return is_file( $wgReadOnlyFile );
334 }
335
336
337 /**
338 * Get a message from anywhere, for the UI elements
339 *
340 * @param string
341 */
342 function wfMsg( $key ) {
343 $args = func_get_args();
344 array_shift( $args );
345 return wfMsgReal( $key, $args, true );
346 }
347
348 /**
349 * Get a message from anywhere, for the content
350 */
351 function wfMsgForContent( $key ) {
352 global $wgForceUIMsgAsContentMsg;
353 $args = func_get_args();
354 array_shift( $args );
355 $forcontent = true;
356 if( is_array( $wgForceUIMsgAsContentMsg ) &&
357 in_array( $key, $wgForceUIMsgAsContentMsg ) )
358 $forcontent = false;
359 return wfMsgReal( $key, $args, true, $forcontent );
360 }
361
362 /**
363 * Get a message from the language file, for the UI elements
364 */
365 function wfMsgNoDB( $key ) {
366 $args = func_get_args();
367 array_shift( $args );
368 return wfMsgReal( $key, $args, false );
369 }
370
371 /**
372 * Get a message from the language file, for the content
373 */
374 function wfMsgNoDBForContent( $key ) {
375 global $wgForceUIMsgAsContentMsg;
376 $args = func_get_args();
377 array_shift( $args );
378 $forcontent = true;
379 if( is_array( $wgForceUIMsgAsContentMsg ) &&
380 in_array( $key, $wgForceUIMsgAsContentMsg ) )
381 $forcontent = false;
382 return wfMsgReal( $key, $args, false, $forcontent );
383 }
384
385
386 /**
387 * Really get a message
388 */
389 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
390 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
391 global $wgParser, $wgMsgParserOptions;
392 global $wgContLang, $wgLanguageCode;
393 global $wgMessageCache, $wgLang;
394
395 $fname = 'wfMsgReal';
396 wfProfileIn( $fname );
397
398 if( is_object( $wgMessageCache ) ) {
399 $message = $wgMessageCache->get( $key, $useDB, $forContent );
400 } else {
401 if( $forContent ) {
402 $lang = &$wgContLang;
403 } else {
404 $lang = &$wgLang;
405 }
406
407 wfSuppressWarnings();
408
409 if( is_object( $lang ) ) {
410 $message = $lang->getMessage( $key );
411 } else {
412 $message = '';
413 }
414 wfRestoreWarnings();
415 if(!$message)
416 $message = Language::getMessage($key);
417 if(strstr($message, '{{' ) !== false) {
418 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
419 }
420 }
421
422 # Replace arguments
423 if( count( $args ) ) {
424 $message = str_replace( $replacementKeys, $args, $message );
425 }
426 wfProfileOut( $fname );
427 return $message;
428 }
429
430
431
432 /**
433 * Just like exit() but makes a note of it.
434 * Commits open transactions except if the error parameter is set
435 */
436 function wfAbruptExit( $error = false ){
437 global $wgLoadBalancer;
438 static $called = false;
439 if ( $called ){
440 exit();
441 }
442 $called = true;
443
444 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
445 $bt = debug_backtrace();
446 for($i = 0; $i < count($bt) ; $i++){
447 $file = $bt[$i]['file'];
448 $line = $bt[$i]['line'];
449 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
450 }
451 } else {
452 wfDebug('WARNING: Abrupt exit\n');
453 }
454 if ( !$error ) {
455 $wgLoadBalancer->closeAll();
456 }
457 exit();
458 }
459
460 /**
461 * @todo document
462 */
463 function wfErrorExit() {
464 wfAbruptExit( true );
465 }
466
467 /**
468 * Die with a backtrace
469 * This is meant as a debugging aid to track down where bad data comes from.
470 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
471 *
472 * @param string $msg Message shown when dieing.
473 */
474 function wfDebugDieBacktrace( $msg = '' ) {
475 global $wgCommandLineMode;
476
477 $backtrace = wfBacktrace();
478 if ( $backtrace !== false ) {
479 if ( $wgCommandLineMode ) {
480 $msg .= "\nBacktrace:\n$backtrace";
481 } else {
482 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
483 }
484 }
485 die( $msg );
486 }
487
488 function wfBacktrace() {
489 global $wgCommandLineMode;
490 if ( !function_exists( 'debug_backtrace' ) ) {
491 return false;
492 }
493
494 if ( $wgCommandLineMode ) {
495 $msg = '';
496 } else {
497 $msg = "<ul>\n";
498 }
499 $backtrace = debug_backtrace();
500 foreach( $backtrace as $call ) {
501 if( isset( $call['file'] ) ) {
502 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
503 $file = $f[count($f)-1];
504 } else {
505 $file = '-';
506 }
507 if( isset( $call['line'] ) ) {
508 $line = $call['line'];
509 } else {
510 $line = '-';
511 }
512 if ( $wgCommandLineMode ) {
513 $msg .= "$file line $line calls ";
514 } else {
515 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
516 }
517 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
518 $msg .= $call['function'] . '()';
519
520 if ( $wgCommandLineMode ) {
521 $msg .= "\n";
522 } else {
523 $msg .= "</li>\n";
524 }
525 }
526 if ( $wgCommandLineMode ) {
527 $msg .= "\n";
528 } else {
529 $msg .= "</ul>\n";
530 }
531
532 return $msg;
533 }
534
535
536 /* Some generic result counters, pulled out of SearchEngine */
537
538
539 /**
540 * @todo document
541 */
542 function wfShowingResults( $offset, $limit ) {
543 global $wgLang;
544 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
545 }
546
547 /**
548 * @todo document
549 */
550 function wfShowingResultsNum( $offset, $limit, $num ) {
551 global $wgLang;
552 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
553 }
554
555 /**
556 * @todo document
557 */
558 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
559 global $wgUser, $wgLang;
560 $fmtLimit = $wgLang->formatNum( $limit );
561 $prev = wfMsg( 'prevn', $fmtLimit );
562 $next = wfMsg( 'nextn', $fmtLimit );
563
564 if( is_object( $link ) ) {
565 $title =& $link;
566 } else {
567 $title =& Title::newFromText( $link );
568 if( is_null( $title ) ) {
569 return false;
570 }
571 }
572
573 $sk = $wgUser->getSkin();
574 if ( 0 != $offset ) {
575 $po = $offset - $limit;
576 if ( $po < 0 ) { $po = 0; }
577 $q = "limit={$limit}&offset={$po}";
578 if ( '' != $query ) { $q .= '&'.$query; }
579 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
580 } else { $plink = $prev; }
581
582 $no = $offset + $limit;
583 $q = 'limit='.$limit.'&offset='.$no;
584 if ( '' != $query ) { $q .= '&'.$query; }
585
586 if ( $atend ) {
587 $nlink = $next;
588 } else {
589 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
590 }
591 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
592 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
593 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
594 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
595 wfNumLink( $offset, 500, $title, $query );
596
597 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
598 }
599
600 /**
601 * @todo document
602 */
603 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
604 global $wgUser, $wgLang;
605 if ( '' == $query ) { $q = ''; }
606 else { $q = $query.'&'; }
607 $q .= 'limit='.$limit.'&offset='.$offset;
608
609 $fmtLimit = $wgLang->formatNum( $limit );
610 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
611 return $s;
612 }
613
614 /**
615 * @todo document
616 * @todo FIXME: we may want to blacklist some broken browsers
617 *
618 * @return bool Whereas client accept gzip compression
619 */
620 function wfClientAcceptsGzip() {
621 global $wgUseGzip;
622 if( $wgUseGzip ) {
623 # FIXME: we may want to blacklist some broken browsers
624 if( preg_match(
625 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
626 $_SERVER['HTTP_ACCEPT_ENCODING'],
627 $m ) ) {
628 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
629 wfDebug( " accepts gzip\n" );
630 return true;
631 }
632 }
633 return false;
634 }
635
636 /**
637 * Yay, more global functions!
638 */
639 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
640 global $wgRequest;
641 return $wgRequest->getLimitOffset( $deflimit, $optionname );
642 }
643
644 /**
645 * Escapes the given text so that it may be output using addWikiText()
646 * without any linking, formatting, etc. making its way through. This
647 * is achieved by substituting certain characters with HTML entities.
648 * As required by the callers, <nowiki> is not used. It currently does
649 * not filter out characters which have special meaning only at the
650 * start of a line, such as "*".
651 *
652 * @param string $text Text to be escaped
653 */
654 function wfEscapeWikiText( $text ) {
655 $text = str_replace(
656 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
657 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
658 htmlspecialchars($text) );
659 return $text;
660 }
661
662 /**
663 * @todo document
664 */
665 function wfQuotedPrintable( $string, $charset = '' ) {
666 # Probably incomplete; see RFC 2045
667 if( empty( $charset ) ) {
668 global $wgInputEncoding;
669 $charset = $wgInputEncoding;
670 }
671 $charset = strtoupper( $charset );
672 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
673
674 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
675 $replace = $illegal . '\t ?_';
676 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
677 $out = "=?$charset?Q?";
678 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
679 $out .= '?=';
680 return $out;
681 }
682
683 /**
684 * Returns an escaped string suitable for inclusion in a string literal
685 * for JavaScript source code.
686 * Illegal control characters are assumed not to be present.
687 *
688 * @param string $string
689 * @return string
690 */
691 function wfEscapeJsString( $string ) {
692 // See ECMA 262 section 7.8.4 for string literal format
693 $pairs = array(
694 "\\" => "\\\\",
695 "\"" => "\\\"",
696 "\'" => "\\\'",
697 "\n" => "\\n",
698 "\r" => "\\r",
699
700 # To avoid closing the element or CDATA section
701 "<" => "\\x3c",
702 ">" => "\\x3e",
703 );
704 return strtr( $string, $pairs );
705 }
706
707 /**
708 * @todo document
709 * @return float
710 */
711 function wfTime() {
712 $st = explode( ' ', microtime() );
713 return (float)$st[0] + (float)$st[1];
714 }
715
716 /**
717 * Changes the first character to an HTML entity
718 */
719 function wfHtmlEscapeFirst( $text ) {
720 $ord = ord($text);
721 $newText = substr($text, 1);
722 return "&#$ord;$newText";
723 }
724
725 /**
726 * Sets dest to source and returns the original value of dest
727 * If source is NULL, it just returns the value, it doesn't set the variable
728 */
729 function wfSetVar( &$dest, $source ) {
730 $temp = $dest;
731 if ( !is_null( $source ) ) {
732 $dest = $source;
733 }
734 return $temp;
735 }
736
737 /**
738 * As for wfSetVar except setting a bit
739 */
740 function wfSetBit( &$dest, $bit, $state = true ) {
741 $temp = (bool)($dest & $bit );
742 if ( !is_null( $state ) ) {
743 if ( $state ) {
744 $dest |= $bit;
745 } else {
746 $dest &= ~$bit;
747 }
748 }
749 return $temp;
750 }
751
752 /**
753 * This function takes two arrays as input, and returns a CGI-style string, e.g.
754 * "days=7&limit=100". Options in the first array override options in the second.
755 * Options set to "" will not be output.
756 */
757 function wfArrayToCGI( $array1, $array2 = NULL )
758 {
759 if ( !is_null( $array2 ) ) {
760 $array1 = $array1 + $array2;
761 }
762
763 $cgi = '';
764 foreach ( $array1 as $key => $value ) {
765 if ( '' !== $value ) {
766 if ( '' != $cgi ) {
767 $cgi .= '&';
768 }
769 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
770 }
771 }
772 return $cgi;
773 }
774
775 /**
776 * This is obsolete, use SquidUpdate::purge()
777 * @deprecated
778 */
779 function wfPurgeSquidServers ($urlArr) {
780 SquidUpdate::purge( $urlArr );
781 }
782
783 /**
784 * Windows-compatible version of escapeshellarg()
785 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
786 * function puts single quotes in regardless of OS
787 */
788 function wfEscapeShellArg( ) {
789 $args = func_get_args();
790 $first = true;
791 $retVal = '';
792 foreach ( $args as $arg ) {
793 if ( !$first ) {
794 $retVal .= ' ';
795 } else {
796 $first = false;
797 }
798
799 if ( wfIsWindows() ) {
800 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
801 } else {
802 $retVal .= escapeshellarg( $arg );
803 }
804 }
805 return $retVal;
806 }
807
808 /**
809 * wfMerge attempts to merge differences between three texts.
810 * Returns true for a clean merge and false for failure or a conflict.
811 */
812 function wfMerge( $old, $mine, $yours, &$result ){
813 global $wgDiff3;
814
815 # This check may also protect against code injection in
816 # case of broken installations.
817 if(! file_exists( $wgDiff3 ) ){
818 return false;
819 }
820
821 # Make temporary files
822 $td = '/tmp/';
823 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
824 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
825 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
826
827 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
828 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
829 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
830
831 # Check for a conflict
832 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
833 wfEscapeShellArg( $mytextName ) . ' ' .
834 wfEscapeShellArg( $oldtextName ) . ' ' .
835 wfEscapeShellArg( $yourtextName );
836 $handle = popen( $cmd, 'r' );
837
838 if( fgets( $handle, 1024 ) ){
839 $conflict = true;
840 } else {
841 $conflict = false;
842 }
843 pclose( $handle );
844
845 # Merge differences
846 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
847 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
848 $handle = popen( $cmd, 'r' );
849 $result = '';
850 do {
851 $data = fread( $handle, 8192 );
852 if ( strlen( $data ) == 0 ) {
853 break;
854 }
855 $result .= $data;
856 } while ( true );
857 pclose( $handle );
858 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
859 return ! $conflict;
860 }
861
862 /**
863 * @todo document
864 */
865 function wfVarDump( $var ) {
866 global $wgOut;
867 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
868 if ( headers_sent() || !@is_object( $wgOut ) ) {
869 print $s;
870 } else {
871 $wgOut->addHTML( $s );
872 }
873 }
874
875 /**
876 * Provide a simple HTTP error.
877 */
878 function wfHttpError( $code, $label, $desc ) {
879 global $wgOut;
880 $wgOut->disable();
881 header( "HTTP/1.0 $code $label" );
882 header( "Status: $code $label" );
883 $wgOut->sendCacheControl();
884
885 header( 'Content-type: text/plain' );
886 print $desc."\n";
887 }
888
889 /**
890 * Converts an Accept-* header into an array mapping string values to quality
891 * factors
892 */
893 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
894 # No arg means accept anything (per HTTP spec)
895 if( !$accept ) {
896 return array( $def => 1 );
897 }
898
899 $prefs = array();
900
901 $parts = explode( ',', $accept );
902
903 foreach( $parts as $part ) {
904 # FIXME: doesn't deal with params like 'text/html; level=1'
905 @list( $value, $qpart ) = explode( ';', $part );
906 if( !isset( $qpart ) ) {
907 $prefs[$value] = 1;
908 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
909 $prefs[$value] = $match[1];
910 }
911 }
912
913 return $prefs;
914 }
915
916 /**
917 * Checks if a given MIME type matches any of the keys in the given
918 * array. Basic wildcards are accepted in the array keys.
919 *
920 * Returns the matching MIME type (or wildcard) if a match, otherwise
921 * NULL if no match.
922 *
923 * @param string $type
924 * @param array $avail
925 * @return string
926 * @access private
927 */
928 function mimeTypeMatch( $type, $avail ) {
929 if( array_key_exists($type, $avail) ) {
930 return $type;
931 } else {
932 $parts = explode( '/', $type );
933 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
934 return $parts[0] . '/*';
935 } elseif( array_key_exists( '*/*', $avail ) ) {
936 return '*/*';
937 } else {
938 return NULL;
939 }
940 }
941 }
942
943 /**
944 * Returns the 'best' match between a client's requested internet media types
945 * and the server's list of available types. Each list should be an associative
946 * array of type to preference (preference is a float between 0.0 and 1.0).
947 * Wildcards in the types are acceptable.
948 *
949 * @param array $cprefs Client's acceptable type list
950 * @param array $sprefs Server's offered types
951 * @return string
952 *
953 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
954 * XXX: generalize to negotiate other stuff
955 */
956 function wfNegotiateType( $cprefs, $sprefs ) {
957 $combine = array();
958
959 foreach( array_keys($sprefs) as $type ) {
960 $parts = explode( '/', $type );
961 if( $parts[1] != '*' ) {
962 $ckey = mimeTypeMatch( $type, $cprefs );
963 if( $ckey ) {
964 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
965 }
966 }
967 }
968
969 foreach( array_keys( $cprefs ) as $type ) {
970 $parts = explode( '/', $type );
971 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
972 $skey = mimeTypeMatch( $type, $sprefs );
973 if( $skey ) {
974 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
975 }
976 }
977 }
978
979 $bestq = 0;
980 $besttype = NULL;
981
982 foreach( array_keys( $combine ) as $type ) {
983 if( $combine[$type] > $bestq ) {
984 $besttype = $type;
985 $bestq = $combine[$type];
986 }
987 }
988
989 return $besttype;
990 }
991
992 /**
993 * Array lookup
994 * Returns an array where the values in the first array are replaced by the
995 * values in the second array with the corresponding keys
996 *
997 * @return array
998 */
999 function wfArrayLookup( $a, $b ) {
1000 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1001 }
1002
1003 /**
1004 * Convenience function; returns MediaWiki timestamp for the present time.
1005 * @return string
1006 */
1007 function wfTimestampNow() {
1008 # return NOW
1009 return wfTimestamp( TS_MW, time() );
1010 }
1011
1012 /**
1013 * Reference-counted warning suppression
1014 */
1015 function wfSuppressWarnings( $end = false ) {
1016 static $suppressCount = 0;
1017 static $originalLevel = false;
1018
1019 if ( $end ) {
1020 if ( $suppressCount ) {
1021 $suppressCount --;
1022 if ( !$suppressCount ) {
1023 error_reporting( $originalLevel );
1024 }
1025 }
1026 } else {
1027 if ( !$suppressCount ) {
1028 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1029 }
1030 $suppressCount++;
1031 }
1032 }
1033
1034 /**
1035 * Restore error level to previous value
1036 */
1037 function wfRestoreWarnings() {
1038 wfSuppressWarnings( true );
1039 }
1040
1041 # Autodetect, convert and provide timestamps of various types
1042
1043 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
1044 define('TS_UNIX',0);
1045 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
1046 define('TS_MW',1);
1047 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
1048 define('TS_DB',2);
1049 /** For HTTP and e-mail headers -- output only */
1050 define('TS_RFC2822', 3 );
1051
1052 /**
1053 * @todo document
1054 */
1055 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1056 if ($ts==0) {
1057 $uts=time();
1058 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1059 # TS_DB
1060 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1061 (int)$da[2],(int)$da[3],(int)$da[1]);
1062 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1063 # TS_MW
1064 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1065 (int)$da[2],(int)$da[3],(int)$da[1]);
1066 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1067 # TS_UNIX
1068 $uts=$ts;
1069 } else {
1070 # Bogus value; fall back to the epoch...
1071 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1072 $uts = 0;
1073 }
1074
1075
1076 switch($outputtype) {
1077 case TS_UNIX:
1078 return $uts;
1079 case TS_MW:
1080 return gmdate( 'YmdHis', $uts );
1081 case TS_DB:
1082 return gmdate( 'Y-m-d H:i:s', $uts );
1083 case TS_RFC2822:
1084 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1085 default:
1086 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1087 }
1088 }
1089
1090 /**
1091 * Return a formatted timestamp, or null if input is null.
1092 * For dealing with nullable timestamp columns in the database.
1093 * @param int $outputtype
1094 * @param string $ts
1095 * @return string
1096 */
1097 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1098 if( is_null( $ts ) ) {
1099 return null;
1100 } else {
1101 return wfTimestamp( $outputtype, $ts );
1102 }
1103 }
1104
1105 /**
1106 * Check where as the operating system is Windows
1107 *
1108 * @return bool True if it's windows, False otherwise.
1109 */
1110 function wfIsWindows() {
1111 if (substr(php_uname(), 0, 7) == 'Windows') {
1112 return true;
1113 } else {
1114 return false;
1115 }
1116 }
1117
1118 /**
1119 * Swap two variables
1120 */
1121 function swap( &$x, &$y ) {
1122 $z = $x;
1123 $x = $y;
1124 $y = $z;
1125 }
1126
1127 function wfGetSiteNotice() {
1128 global $wgSiteNotice, $wgTitle, $wgOut;
1129 $fname = 'wfGetSiteNotice';
1130 wfProfileIn( $fname );
1131
1132 $notice = wfMsg( 'sitenotice' );
1133 if($notice == '&lt;sitenotice&gt;') $notice = '';
1134 # Allow individual wikis to turn it off
1135 if ( $notice == '-' ) {
1136 $notice = '';
1137 } else {
1138 if ($notice == '') {
1139 $notice = $wgSiteNotice;
1140 }
1141 if($notice != '-' && $notice != '') {
1142 $specialparser = new Parser();
1143 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1144 $notice = $parserOutput->getText();
1145 }
1146 }
1147 wfProfileOut( $fname );
1148 return $notice;
1149 }
1150
1151 /**
1152 * Format an XML element with given attributes and, optionally, text content.
1153 * Element and attribute names are assumed to be ready for literal inclusion.
1154 * Strings are assumed to not contain XML-illegal characters; special
1155 * characters (<, >, &) are escaped but illegals are not touched.
1156 *
1157 * @param string $element
1158 * @param array $attribs Name=>value pairs. Values will be escaped.
1159 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1160 * @return string
1161 */
1162 function wfElement( $element, $attribs = array(), $contents = '') {
1163 $out = '<' . $element;
1164 foreach( $attribs as $name => $val ) {
1165 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1166 }
1167 if( is_null( $contents ) ) {
1168 $out .= '>';
1169 } else {
1170 if( $contents == '' ) {
1171 $out .= ' />';
1172 } else {
1173 $out .= '>';
1174 $out .= htmlspecialchars( $contents );
1175 $out .= "</$element>";
1176 }
1177 }
1178 return $out;
1179 }
1180
1181 ?>