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