first attempt to support multiple language variants in the MediaWiki: namespace.
[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(strstr($message, '{{' ) !== false) {
449 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
450 }
451 } else {
452 wfDebug( "No language object when getting $key\n" );
453 $message = "&lt;$key&gt;";
454 }
455
456 # Replace arguments
457 if( count( $args ) ) {
458 $message = str_replace( $wgReplacementKeys, $args, $message );
459 }
460 wfProfileOut( $fname );
461 return $message;
462 }
463
464
465
466 /**
467 * Just like exit() but makes a note of it.
468 * Commits open transactions except if the error parameter is set
469 */
470 function wfAbruptExit( $error = false ){
471 global $wgLoadBalancer;
472 static $called = false;
473 if ( $called ){
474 exit();
475 }
476 $called = true;
477
478 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
479 $bt = debug_backtrace();
480 for($i = 0; $i < count($bt) ; $i++){
481 $file = $bt[$i]['file'];
482 $line = $bt[$i]['line'];
483 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
484 }
485 } else {
486 wfDebug('WARNING: Abrupt exit\n');
487 }
488 if ( !$error ) {
489 $wgLoadBalancer->closeAll();
490 }
491 exit();
492 }
493
494 /**
495 * @todo document
496 */
497 function wfErrorExit() {
498 wfAbruptExit( true );
499 }
500
501 /**
502 * Die with a backtrace
503 * This is meant as a debugging aid to track down where bad data comes from.
504 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
505 *
506 * @param string $msg Message shown when dieing.
507 */
508 function wfDebugDieBacktrace( $msg = '' ) {
509 global $wgCommandLineMode;
510
511 if ( function_exists( 'debug_backtrace' ) ) {
512 if ( $wgCommandLineMode ) {
513 $msg .= "\nBacktrace:\n";
514 } else {
515 $msg .= "\n<p>Backtrace:</p>\n<ul>\n";
516 }
517 $backtrace = debug_backtrace();
518 foreach( $backtrace as $call ) {
519 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
520 $file = $f[count($f)-1];
521 if ( $wgCommandLineMode ) {
522 $msg .= "$file line {$call['line']} calls ";
523 } else {
524 $msg .= '<li>' . $file . ' line ' . $call['line'] . ' calls ';
525 }
526 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
527 $msg .= $call['function'] . '()';
528
529 if ( $wgCommandLineMode ) {
530 $msg .= "\n";
531 } else {
532 $msg .= "</li>\n";
533 }
534 }
535 }
536 die( $msg );
537 }
538
539
540 /* Some generic result counters, pulled out of SearchEngine */
541
542
543 /**
544 * @todo document
545 */
546 function wfShowingResults( $offset, $limit ) {
547 global $wgLang;
548 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
549 }
550
551 /**
552 * @todo document
553 */
554 function wfShowingResultsNum( $offset, $limit, $num ) {
555 global $wgLang;
556 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
557 }
558
559 /**
560 * @todo document
561 */
562 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
563 global $wgUser, $wgLang;
564 $fmtLimit = $wgLang->formatNum( $limit );
565 $prev = wfMsg( 'prevn', $fmtLimit );
566 $next = wfMsg( 'nextn', $fmtLimit );
567 $link = wfUrlencode( $link );
568
569 $sk = $wgUser->getSkin();
570 if ( 0 != $offset ) {
571 $po = $offset - $limit;
572 if ( $po < 0 ) { $po = 0; }
573 $q = "limit={$limit}&offset={$po}";
574 if ( '' != $query ) { $q .= '&'.$query; }
575 $plink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
576 } else { $plink = $prev; }
577
578 $no = $offset + $limit;
579 $q = 'limit='.$limit.'&offset='.$no;
580 if ( '' != $query ) { $q .= '&'.$query; }
581
582 if ( $atend ) {
583 $nlink = $next;
584 } else {
585 $nlink = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
586 }
587 $nums = wfNumLink( $offset, 20, $link , $query ) . ' | ' .
588 wfNumLink( $offset, 50, $link, $query ) . ' | ' .
589 wfNumLink( $offset, 100, $link, $query ) . ' | ' .
590 wfNumLink( $offset, 250, $link, $query ) . ' | ' .
591 wfNumLink( $offset, 500, $link, $query );
592
593 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
594 }
595
596 /**
597 * @todo document
598 */
599 function wfNumLink( $offset, $limit, $link, $query = '' ) {
600 global $wgUser, $wgLang;
601 if ( '' == $query ) { $q = ''; }
602 else { $q = $query.'&'; }
603 $q .= 'limit='.$limit.'&offset='.$offset;
604
605 $fmtLimit = $wgLang->formatNum( $limit );
606 $s = '<a href="' . wfLocalUrlE( $link, $q ) . "\">{$fmtLimit}</a>";
607 return $s;
608 }
609
610 /**
611 * @todo document
612 * @todo FIXME: we may want to blacklist some broken browsers
613 *
614 * @return bool Whereas client accept gzip compression
615 */
616 function wfClientAcceptsGzip() {
617 global $wgUseGzip;
618 if( $wgUseGzip ) {
619 # FIXME: we may want to blacklist some broken browsers
620 if( preg_match(
621 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
622 $_SERVER['HTTP_ACCEPT_ENCODING'],
623 $m ) ) {
624 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
625 wfDebug( " accepts gzip\n" );
626 return true;
627 }
628 }
629 return false;
630 }
631
632 /**
633 * Yay, more global functions!
634 */
635 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
636 global $wgRequest;
637 return $wgRequest->getLimitOffset( $deflimit, $optionname );
638 }
639
640 /**
641 * Escapes the given text so that it may be output using addWikiText()
642 * without any linking, formatting, etc. making its way through. This
643 * is achieved by substituting certain characters with HTML entities.
644 * As required by the callers, <nowiki> is not used. It currently does
645 * not filter out characters which have special meaning only at the
646 * start of a line, such as "*".
647 *
648 * @param string $text Text to be escaped
649 */
650 function wfEscapeWikiText( $text ) {
651 $text = str_replace(
652 array( '[', '|', "'", 'ISBN ' , '://' , "\n=", '{{' ),
653 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
654 htmlspecialchars($text) );
655 return $text;
656 }
657
658 /**
659 * @todo document
660 */
661 function wfQuotedPrintable( $string, $charset = '' ) {
662 # Probably incomplete; see RFC 2045
663 if( empty( $charset ) ) {
664 global $wgInputEncoding;
665 $charset = $wgInputEncoding;
666 }
667 $charset = strtoupper( $charset );
668 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
669
670 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
671 $replace = $illegal . '\t ?_';
672 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
673 $out = "=?$charset?Q?";
674 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
675 $out .= '?=';
676 return $out;
677 }
678
679 /**
680 * @todo document
681 * @return float
682 */
683 function wfTime() {
684 $st = explode( ' ', microtime() );
685 return (float)$st[0] + (float)$st[1];
686 }
687
688 /**
689 * Changes the first character to an HTML entity
690 */
691 function wfHtmlEscapeFirst( $text ) {
692 $ord = ord($text);
693 $newText = substr($text, 1);
694 return "&#$ord;$newText";
695 }
696
697 /**
698 * Sets dest to source and returns the original value of dest
699 * If source is NULL, it just returns the value, it doesn't set the variable
700 */
701 function wfSetVar( &$dest, $source ) {
702 $temp = $dest;
703 if ( !is_null( $source ) ) {
704 $dest = $source;
705 }
706 return $temp;
707 }
708
709 /**
710 * As for wfSetVar except setting a bit
711 */
712 function wfSetBit( &$dest, $bit, $state = true ) {
713 $temp = (bool)($dest & $bit );
714 if ( !is_null( $state ) ) {
715 if ( $state ) {
716 $dest |= $bit;
717 } else {
718 $dest &= ~$bit;
719 }
720 }
721 return $temp;
722 }
723
724 /**
725 * This function takes two arrays as input, and returns a CGI-style string, e.g.
726 * "days=7&limit=100". Options in the first array override options in the second.
727 * Options set to "" will not be output.
728 */
729 function wfArrayToCGI( $array1, $array2 = NULL )
730 {
731 if ( !is_null( $array2 ) ) {
732 $array1 = $array1 + $array2;
733 }
734
735 $cgi = '';
736 foreach ( $array1 as $key => $value ) {
737 if ( '' !== $value ) {
738 if ( '' != $cgi ) {
739 $cgi .= '&';
740 }
741 $cgi .= $key.'='.$value;
742 }
743 }
744 return $cgi;
745 }
746
747 /**
748 * This is obsolete, use SquidUpdate::purge()
749 * @deprecated
750 */
751 function wfPurgeSquidServers ($urlArr) {
752 SquidUpdate::purge( $urlArr );
753 }
754
755 /**
756 * Windows-compatible version of escapeshellarg()
757 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
758 * function puts single quotes in regardless of OS
759 */
760 function wfEscapeShellArg( ) {
761 $args = func_get_args();
762 $first = true;
763 $retVal = '';
764 foreach ( $args as $arg ) {
765 if ( !$first ) {
766 $retVal .= ' ';
767 } else {
768 $first = false;
769 }
770
771 if ( wfIsWindows() ) {
772 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
773 } else {
774 $retVal .= escapeshellarg( $arg );
775 }
776 }
777 return $retVal;
778 }
779
780 /**
781 * wfMerge attempts to merge differences between three texts.
782 * Returns true for a clean merge and false for failure or a conflict.
783 */
784 function wfMerge( $old, $mine, $yours, &$result ){
785 global $wgDiff3;
786
787 # This check may also protect against code injection in
788 # case of broken installations.
789 if(! file_exists( $wgDiff3 ) ){
790 return false;
791 }
792
793 # Make temporary files
794 $td = '/tmp/';
795 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
796 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
797 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
798
799 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
800 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
801 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
802
803 # Check for a conflict
804 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
805 wfEscapeShellArg( $mytextName ) . ' ' .
806 wfEscapeShellArg( $oldtextName ) . ' ' .
807 wfEscapeShellArg( $yourtextName );
808 $handle = popen( $cmd, 'r' );
809
810 if( fgets( $handle ) ){
811 $conflict = true;
812 } else {
813 $conflict = false;
814 }
815 pclose( $handle );
816
817 # Merge differences
818 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
819 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
820 $handle = popen( $cmd, 'r' );
821 $result = '';
822 do {
823 $data = fread( $handle, 8192 );
824 if ( strlen( $data ) == 0 ) {
825 break;
826 }
827 $result .= $data;
828 } while ( true );
829 pclose( $handle );
830 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
831 return ! $conflict;
832 }
833
834 /**
835 * @todo document
836 */
837 function wfVarDump( $var ) {
838 global $wgOut;
839 $s = str_replace("\n","<br>\n", var_export( $var, true ) . "\n");
840 if ( headers_sent() || !@is_object( $wgOut ) ) {
841 print $s;
842 } else {
843 $wgOut->addHTML( $s );
844 }
845 }
846
847 /**
848 * Provide a simple HTTP error.
849 */
850 function wfHttpError( $code, $label, $desc ) {
851 global $wgOut;
852 $wgOut->disable();
853 header( "HTTP/1.0 $code $label" );
854 header( "Status: $code $label" );
855 $wgOut->sendCacheControl();
856
857 # Don't send content if it's a HEAD request.
858 if( $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
859 header( 'Content-type: text/plain' );
860 print "$desc\n";
861 }
862 }
863
864 /**
865 * Converts an Accept-* header into an array mapping string values to quality
866 * factors
867 */
868 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
869 # No arg means accept anything (per HTTP spec)
870 if( !$accept ) {
871 return array( $def => 1 );
872 }
873
874 $prefs = array();
875
876 $parts = explode( ',', $accept );
877
878 foreach( $parts as $part ) {
879 # FIXME: doesn't deal with params like 'text/html; level=1'
880 @list( $value, $qpart ) = explode( ';', $part );
881 if( !isset( $qpart ) ) {
882 $prefs[$value] = 1;
883 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
884 $prefs[$value] = $match[1];
885 }
886 }
887
888 return $prefs;
889 }
890
891 /**
892 * @todo document
893 * @private
894 */
895 function mimeTypeMatch( $type, $avail ) {
896 if( array_key_exists($type, $avail) ) {
897 return $type;
898 } else {
899 $parts = explode( '/', $type );
900 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
901 return $parts[0] . '/*';
902 } elseif( array_key_exists( '*/*', $avail ) ) {
903 return '*/*';
904 } else {
905 return NULL;
906 }
907 }
908 }
909
910 /**
911 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
912 * XXX: generalize to negotiate other stuff
913 */
914 function wfNegotiateType( $cprefs, $sprefs ) {
915 $combine = array();
916
917 foreach( array_keys($sprefs) as $type ) {
918 $parts = explode( '/', $type );
919 if( $parts[1] != '*' ) {
920 $ckey = mimeTypeMatch( $type, $cprefs );
921 if( $ckey ) {
922 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
923 }
924 }
925 }
926
927 foreach( array_keys( $cprefs ) as $type ) {
928 $parts = explode( '/', $type );
929 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
930 $skey = mimeTypeMatch( $type, $sprefs );
931 if( $skey ) {
932 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
933 }
934 }
935 }
936
937 $bestq = 0;
938 $besttype = NULL;
939
940 foreach( array_keys( $combine ) as $type ) {
941 if( $combine[$type] > $bestq ) {
942 $besttype = $type;
943 $bestq = $combine[$type];
944 }
945 }
946
947 return $besttype;
948 }
949
950 /**
951 * Array lookup
952 * Returns an array where the values in the first array are replaced by the
953 * values in the second array with the corresponding keys
954 *
955 * @return array
956 */
957 function wfArrayLookup( $a, $b ) {
958 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
959 }
960
961
962 /**
963 * Ideally we'd be using actual time fields in the db
964 * @todo fixme
965 */
966 function wfTimestamp2Unix( $ts ) {
967 return gmmktime( ( (int)substr( $ts, 8, 2) ),
968 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
969 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
970 (int)substr( $ts, 0, 4 ) );
971 }
972
973 /**
974 * @todo document
975 */
976 function wfUnix2Timestamp( $unixtime ) {
977 return gmdate( 'YmdHis', $unixtime );
978 }
979
980 /**
981 * @todo document
982 */
983 function wfTimestampNow() {
984 # return NOW
985 return gmdate( 'YmdHis' );
986 }
987
988 /**
989 * Sorting hack for MySQL 3, which doesn't use index sorts for DESC
990 */
991 function wfInvertTimestamp( $ts ) {
992 return strtr(
993 $ts,
994 '0123456789',
995 '9876543210'
996 );
997 }
998
999 /**
1000 * Reference-counted warning suppression
1001 */
1002 function wfSuppressWarnings( $end = false ) {
1003 static $suppressCount = 0;
1004 static $originalLevel = false;
1005
1006 if ( $end ) {
1007 if ( $suppressCount ) {
1008 $suppressCount --;
1009 if ( !$suppressCount ) {
1010 error_reporting( $originalLevel );
1011 }
1012 }
1013 } else {
1014 if ( !$suppressCount ) {
1015 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1016 }
1017 $suppressCount++;
1018 }
1019 }
1020
1021 /**
1022 * Restore error level to previous value
1023 */
1024 function wfRestoreWarnings() {
1025 wfSuppressWarnings( true );
1026 }
1027
1028 # Autodetect, convert and provide timestamps of various types
1029
1030 /** Standard unix timestamp (number of seconds since 1 Jan 1970) */
1031 define('TS_UNIX',0);
1032 /** MediaWiki concatenated string timestamp (yyyymmddhhmmss) */
1033 define('TS_MW',1);
1034 /** Standard database timestamp (yyyy-mm-dd hh:mm:ss) */
1035 define('TS_DB',2);
1036
1037 /**
1038 * @todo document
1039 */
1040 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1041 if (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1042 # TS_DB
1043 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1044 (int)$da[2],(int)$da[3],(int)$da[1]);
1045 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1046 # TS_MW
1047 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1048 (int)$da[2],(int)$da[3],(int)$da[1]);
1049 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1050 # TS_UNIX
1051 $uts=$ts;
1052 }
1053
1054 if ($ts==0)
1055 $uts=time();
1056 switch($outputtype) {
1057 case TS_UNIX:
1058 return $uts;
1059 break;
1060 case TS_MW:
1061 return gmdate( 'YmdHis', $uts );
1062 break;
1063 case TS_DB:
1064 return gmdate( 'Y-m-d H:i:s', $uts );
1065 break;
1066 default:
1067 return;
1068 }
1069 }
1070
1071 /**
1072 * Check where as the operating system is Windows
1073 *
1074 * @todo document
1075 * @return bool True if it's windows, False otherwise.
1076 */
1077 function wfIsWindows() {
1078 if (substr(php_uname(), 0, 7) == 'Windows') {
1079 return true;
1080 } else {
1081 return false;
1082 }
1083 }
1084
1085 ?>