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