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