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