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