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