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