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