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