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