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