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