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