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