]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/GlobalFunctions.php
MediaWiki 1.14.0
[autoinstalls/mediawiki.git] / includes / GlobalFunctions.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4         die( "This file is part of MediaWiki, it is not a valid entry point" );
5 }
6
7 /**
8  * Global functions used everywhere
9  */
10
11 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
12 require_once dirname(__FILE__) . '/XmlFunctions.php';
13
14 // Hide compatibility functions from Doxygen
15 /// @cond
16
17 /**
18  * Compatibility functions
19  *
20  * We more or less support PHP 5.0.x and up.
21  * Re-implementations of newer functions or functions in non-standard
22  * PHP extensions may be included here.
23  */
24 if( !function_exists('iconv') ) {
25         # iconv support is not in the default configuration and so may not be present.
26         # Assume will only ever use utf-8 and iso-8859-1.
27         # This will *not* work in all circumstances.
28         function iconv( $from, $to, $string ) {
29                 if(strcasecmp( $from, $to ) == 0) return $string;
30                 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
31                 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
32                 return $string;
33         }
34 }
35
36 # UTF-8 substr function based on a PHP manual comment
37 if ( !function_exists( 'mb_substr' ) ) {
38         function mb_substr( $str, $start ) {
39                 $ar = array();
40                 preg_match_all( '/./us', $str, $ar );
41
42                 if( func_num_args() >= 3 ) {
43                         $end = func_get_arg( 2 );
44                         return join( '', array_slice( $ar[0], $start, $end ) );
45                 } else {
46                         return join( '', array_slice( $ar[0], $start ) );
47                 }
48         }
49 }
50
51 if ( !function_exists( 'mb_strlen' ) ) {
52         /**
53          * Fallback implementation of mb_strlen, hardcoded to UTF-8.
54          * @param string $str
55          * @param string $enc optional encoding; ignored
56          * @return int
57          */
58         function mb_strlen( $str, $enc="" ) {
59                 $counts = count_chars( $str );
60                 $total = 0;
61
62                 // Count ASCII bytes
63                 for( $i = 0; $i < 0x80; $i++ ) {
64                         $total += $counts[$i];
65                 }
66
67                 // Count multibyte sequence heads
68                 for( $i = 0xc0; $i < 0xff; $i++ ) {
69                         $total += $counts[$i];
70                 }
71                 return $total;
72         }
73 }
74
75 if ( !function_exists( 'array_diff_key' ) ) {
76         /**
77          * Exists in PHP 5.1.0+
78          * Not quite compatible, two-argument version only
79          * Null values will cause problems due to this use of isset()
80          */
81         function array_diff_key( $left, $right ) {
82                 $result = $left;
83                 foreach ( $left as $key => $unused ) {
84                         if ( isset( $right[$key] ) ) {
85                                 unset( $result[$key] );
86                         }
87                 }
88                 return $result;
89         }
90 }
91
92 /// @endcond
93
94
95 /**
96  * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
97  */
98 function wfArrayDiff2( $a, $b ) {
99         return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
100 }
101 function wfArrayDiff2_cmp( $a, $b ) {
102         if ( !is_array( $a ) ) {
103                 return strcmp( $a, $b );
104         } elseif ( count( $a ) !== count( $b ) ) {
105                 return count( $a ) < count( $b ) ? -1 : 1;
106         } else {
107                 reset( $a );
108                 reset( $b );
109                 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
110                         $cmp = strcmp( $valueA, $valueB );
111                         if ( $cmp !== 0 ) {
112                                 return $cmp;
113                         }
114                 }
115                 return 0;
116         }
117 }
118
119 /**
120  * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
121  * PHP 5 won't let you declare a 'clone' function, even conditionally,
122  * so it has to be a wrapper with a different name.
123  */
124 function wfClone( $object ) {
125         return clone( $object );
126 }
127
128 /**
129  * Seed Mersenne Twister
130  * No-op for compatibility; only necessary in PHP < 4.2.0
131  */
132 function wfSeedRandom() {
133         /* No-op */
134 }
135
136 /**
137  * Get a random decimal value between 0 and 1, in a way
138  * not likely to give duplicate values for any realistic
139  * number of articles.
140  *
141  * @return string
142  */
143 function wfRandom() {
144         # The maximum random value is "only" 2^31-1, so get two random
145         # values to reduce the chance of dupes
146         $max = mt_getrandmax() + 1;
147         $rand = number_format( (mt_rand() * $max + mt_rand())
148                 / $max / $max, 12, '.', '' );
149         return $rand;
150 }
151
152 /**
153  * We want some things to be included as literal characters in our title URLs
154  * for prettiness, which urlencode encodes by default.  According to RFC 1738,
155  * all of the following should be safe:
156  *
157  * ;:@&=$-_.+!*'(),
158  *
159  * But + is not safe because it's used to indicate a space; &= are only safe in
160  * paths and not in queries (and we don't distinguish here); ' seems kind of
161  * scary; and urlencode() doesn't touch -_. to begin with.  Plus, although /
162  * is reserved, we don't care.  So the list we unescape is:
163  *
164  * ;:@$!*(),/
165  *
166  * %2F in the page titles seems to fatally break for some reason.
167  *
168  * @param $s String:
169  * @return string
170 */
171 function wfUrlencode( $s ) {
172         $s = urlencode( $s );
173         $s = str_ireplace(
174                 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
175                 array(   ';',  ':',  '@',  '$',  '!',  '*',  '(',  ')',  ',',  '/' ),
176                 $s
177         );
178
179         return $s;
180 }
181
182 /**
183  * Sends a line to the debug log if enabled or, optionally, to a comment in output.
184  * In normal operation this is a NOP.
185  *
186  * Controlling globals:
187  * $wgDebugLogFile - points to the log file
188  * $wgProfileOnly - if set, normal debug messages will not be recorded.
189  * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
190  * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
191  *
192  * @param $text String
193  * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
194  */
195 function wfDebug( $text, $logonly = false ) {
196         global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
197         global $wgDebugLogPrefix;
198         static $recursion = 0;
199
200         static $cache = array(); // Cache of unoutputted messages
201
202         # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
203         if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
204                 return;
205         }
206
207         if ( $wgDebugComments && !$logonly ) {
208                 $cache[] = $text;
209
210                 if ( !isset( $wgOut ) ) {
211                         return;
212                 }
213                 if ( !StubObject::isRealObject( $wgOut ) ) {
214                         if ( $recursion ) {
215                                 return;
216                         }
217                         $recursion++;
218                         $wgOut->_unstub();
219                         $recursion--;
220                 }
221
222                 // add the message and possible cached ones to the output
223                 array_map( array( $wgOut, 'debug' ), $cache );
224                 $cache = array();
225         }
226         if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
227                 # Strip unprintables; they can switch terminal modes when binary data
228                 # gets dumped, which is pretty annoying.
229                 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
230                 $text = $wgDebugLogPrefix . $text;
231                 wfErrorLog( $text, $wgDebugLogFile );
232         }
233 }
234
235 /**
236  * Send a line giving PHP memory usage.
237  * @param $exact Bool : print exact values instead of kilobytes (default: false)
238  */
239 function wfDebugMem( $exact = false ) {
240         $mem = memory_get_usage();
241         if( !$exact ) {
242                 $mem = floor( $mem / 1024 ) . ' kilobytes';
243         } else {
244                 $mem .= ' bytes';
245         }
246         wfDebug( "Memory usage: $mem\n" );
247 }
248
249 /**
250  * Send a line to a supplementary debug log file, if configured, or main debug log if not.
251  * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
252  *
253  * @param $logGroup String
254  * @param $text String
255  * @param $public Bool: whether to log the event in the public log if no private
256  *                     log file is specified, (default true)
257  */
258 function wfDebugLog( $logGroup, $text, $public = true ) {
259         global $wgDebugLogGroups, $wgShowHostnames;
260         $text = trim($text)."\n";
261         if( isset( $wgDebugLogGroups[$logGroup] ) ) {
262                 $time = wfTimestamp( TS_DB );
263                 $wiki = wfWikiID();
264                 if ( $wgShowHostnames ) {
265                         $host = wfHostname();
266                 } else {
267                         $host = '';
268                 }
269                 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
270         } else if ( $public === true ) {
271                 wfDebug( $text, true );
272         }
273 }
274
275 /**
276  * Log for database errors
277  * @param $text String: database error message.
278  */
279 function wfLogDBError( $text ) {
280         global $wgDBerrorLog, $wgDBname;
281         if ( $wgDBerrorLog ) {
282                 $host = trim(`hostname`);
283                 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
284                 wfErrorLog( $text, $wgDBerrorLog );
285         }
286 }
287
288 /**
289  * Log to a file without getting "file size exceeded" signals.
290  * 
291  * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will 
292  * send lines to the specified port, prefixed by the specified prefix and a space.
293  */
294 function wfErrorLog( $text, $file ) {
295         if ( substr( $file, 0, 4 ) == 'udp:' ) {
296                 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
297                         // IPv6 bracketed host
298                         $protocol = $m[1];
299                         $host = $m[2];
300                         $port = $m[3];
301                         $prefix = isset( $m[4] ) ? $m[4] : false;
302                 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
303                         $protocol = $m[1];
304                         $host = $m[2];
305                         $port = $m[3];
306                         $prefix = isset( $m[4] ) ? $m[4] : false;
307                 } else {
308                         throw new MWException( __METHOD__.": Invalid UDP specification" );
309                 }
310                 // Clean it up for the multiplexer
311                 if ( strval( $prefix ) !== '' ) {
312                         $text = preg_replace( '/^/m', $prefix . ' ', $text );
313                         if ( substr( $text, -1 ) != "\n" ) {
314                                 $text .= "\n";
315                         }
316                 }
317
318                 $sock = fsockopen( "$protocol://$host", $port );
319                 if ( !$sock ) {
320                         return;
321                 }
322                 fwrite( $sock, $text );
323                 fclose( $sock );
324         } else {
325                 wfSuppressWarnings();
326                 $exists = file_exists( $file );
327                 $size = $exists ? filesize( $file ) : false;
328                 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
329                         error_log( $text, 3, $file );
330                 }
331                 wfRestoreWarnings();
332         }
333 }
334
335 /**
336  * @todo document
337  */
338 function wfLogProfilingData() {
339         global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
340         global $wgProfiler, $wgUser;
341         if ( !isset( $wgProfiler ) )
342                 return;
343
344         $now = wfTime();
345         $elapsed = $now - $wgRequestTime;
346         $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
347         $forward = '';
348         if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
349                 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
350         if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
351                 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
352         if( !empty( $_SERVER['HTTP_FROM'] ) )
353                 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
354         if( $forward )
355                 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
356         // Don't unstub $wgUser at this late stage just for statistics purposes
357         if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
358                 $forward .= ' anon';
359         $log = sprintf( "%s\t%04.3f\t%s\n",
360           gmdate( 'YmdHis' ), $elapsed,
361           urldecode( $wgRequest->getRequestURL() . $forward ) );
362         if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
363                 wfErrorLog( $log . $prof, $wgDebugLogFile );
364         }
365 }
366
367 /**
368  * Check if the wiki read-only lock file is present. This can be used to lock
369  * off editing functions, but doesn't guarantee that the database will not be
370  * modified.
371  * @return bool
372  */
373 function wfReadOnly() {
374         global $wgReadOnlyFile, $wgReadOnly;
375
376         if ( !is_null( $wgReadOnly ) ) {
377                 return (bool)$wgReadOnly;
378         }
379         if ( '' == $wgReadOnlyFile ) {
380                 return false;
381         }
382         // Set $wgReadOnly for faster access next time
383         if ( is_file( $wgReadOnlyFile ) ) {
384                 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
385         } else {
386                 $wgReadOnly = false;
387         }
388         return (bool)$wgReadOnly;
389 }
390
391 function wfReadOnlyReason() {
392         global $wgReadOnly;
393         wfReadOnly();
394         return $wgReadOnly;
395 }
396
397 /**
398  * Return a Language object from $langcode
399  * @param $langcode Mixed: either:
400  *                  - a Language object
401  *                  - code of the language to get the message for, if it is
402  *                    a valid code create a language for that language, if
403  *                    it is a string but not a valid code then make a basic
404  *                    language object
405  *                  - a boolean: if it's false then use the current users
406  *                    language (as a fallback for the old parameter
407  *                    functionality), or if it is true then use the wikis
408  * @return Language object
409  */
410 function wfGetLangObj( $langcode = false ){
411         # Identify which language to get or create a language object for.
412         if( $langcode instanceof Language )
413                 # Great, we already have the object!
414                 return $langcode;
415                 
416         global $wgContLang;
417         if( $langcode === $wgContLang->getCode() || $langcode === true )
418                 # $langcode is the language code of the wikis content language object.
419                 # or it is a boolean and value is true
420                 return $wgContLang;
421         
422         global $wgLang;
423         if( $langcode === $wgLang->getCode() || $langcode === false )
424                 # $langcode is the language code of user language object.
425                 # or it was a boolean and value is false
426                 return $wgLang;
427
428         $validCodes = array_keys( Language::getLanguageNames() );
429         if( in_array( $langcode, $validCodes ) )
430                 # $langcode corresponds to a valid language.
431                 return Language::factory( $langcode );
432
433         # $langcode is a string, but not a valid language code; use content language.
434         wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
435         return $wgContLang;
436 }
437
438 /**
439  * Get a message from anywhere, for the current user language.
440  *
441  * Use wfMsgForContent() instead if the message should NOT
442  * change depending on the user preferences.
443  *
444  * @param $key String: lookup key for the message, usually
445  *    defined in languages/Language.php
446  *
447  * This function also takes extra optional parameters (not
448  * shown in the function definition), which can by used to
449  * insert variable text into the predefined message.
450  */
451 function wfMsg( $key ) {
452         $args = func_get_args();
453         array_shift( $args );
454         return wfMsgReal( $key, $args, true );
455 }
456
457 /**
458  * Same as above except doesn't transform the message
459  */
460 function wfMsgNoTrans( $key ) {
461         $args = func_get_args();
462         array_shift( $args );
463         return wfMsgReal( $key, $args, true, false, false );
464 }
465
466 /**
467  * Get a message from anywhere, for the current global language
468  * set with $wgLanguageCode.
469  *
470  * Use this if the message should NOT change  dependent on the
471  * language set in the user's preferences. This is the case for
472  * most text written into logs, as well as link targets (such as
473  * the name of the copyright policy page). Link titles, on the
474  * other hand, should be shown in the UI language.
475  *
476  * Note that MediaWiki allows users to change the user interface
477  * language in their preferences, but a single installation
478  * typically only contains content in one language.
479  *
480  * Be wary of this distinction: If you use wfMsg() where you should
481  * use wfMsgForContent(), a user of the software may have to
482  * customize over 70 messages in order to, e.g., fix a link in every
483  * possible language.
484  *
485  * @param $key String: lookup key for the message, usually
486  *    defined in languages/Language.php
487  */
488 function wfMsgForContent( $key ) {
489         global $wgForceUIMsgAsContentMsg;
490         $args = func_get_args();
491         array_shift( $args );
492         $forcontent = true;
493         if( is_array( $wgForceUIMsgAsContentMsg ) &&
494                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
495                 $forcontent = false;
496         return wfMsgReal( $key, $args, true, $forcontent );
497 }
498
499 /**
500  * Same as above except doesn't transform the message
501  */
502 function wfMsgForContentNoTrans( $key ) {
503         global $wgForceUIMsgAsContentMsg;
504         $args = func_get_args();
505         array_shift( $args );
506         $forcontent = true;
507         if( is_array( $wgForceUIMsgAsContentMsg ) &&
508                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
509                 $forcontent = false;
510         return wfMsgReal( $key, $args, true, $forcontent, false );
511 }
512
513 /**
514  * Get a message from the language file, for the UI elements
515  */
516 function wfMsgNoDB( $key ) {
517         $args = func_get_args();
518         array_shift( $args );
519         return wfMsgReal( $key, $args, false );
520 }
521
522 /**
523  * Get a message from the language file, for the content
524  */
525 function wfMsgNoDBForContent( $key ) {
526         global $wgForceUIMsgAsContentMsg;
527         $args = func_get_args();
528         array_shift( $args );
529         $forcontent = true;
530         if( is_array( $wgForceUIMsgAsContentMsg ) &&
531                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
532                 $forcontent = false;
533         return wfMsgReal( $key, $args, false, $forcontent );
534 }
535
536
537 /**
538  * Really get a message
539  * @param $key String: key to get.
540  * @param $args
541  * @param $useDB Boolean
542  * @param $transform Boolean: Whether or not to transform the message.
543  * @param $forContent Boolean
544  * @return String: the requested message.
545  */
546 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
547         wfProfileIn( __METHOD__ );
548         $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
549         $message = wfMsgReplaceArgs( $message, $args );
550         wfProfileOut( __METHOD__ );
551         return $message;
552 }
553
554 /**
555  * This function provides the message source for messages to be edited which are *not* stored in the database.
556  * @param $key String:
557  */
558 function wfMsgWeirdKey ( $key ) {
559         $source = wfMsgGetKey( $key, false, true, false );
560         if ( wfEmptyMsg( $key, $source ) )
561                 return "";
562         else
563                 return $source;
564 }
565
566 /**
567  * Fetch a message string value, but don't replace any keys yet.
568  * @param string $key
569  * @param bool $useDB
570  * @param string $langcode Code of the language to get the message for, or
571  *                         behaves as a content language switch if it is a
572  *                         boolean.
573  * @return string
574  * @private
575  */
576 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
577         global $wgContLang, $wgMessageCache;
578
579         wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
580         
581         # If $wgMessageCache isn't initialised yet, try to return something sensible.
582         if( is_object( $wgMessageCache ) ) {
583                 $message = $wgMessageCache->get( $key, $useDB, $langCode );
584                 if ( $transform ) {
585                         $message = $wgMessageCache->transform( $message );
586                 }
587         } else {
588                 $lang = wfGetLangObj( $langCode );
589
590                 # MessageCache::get() does this already, Language::getMessage() doesn't
591                 # ISSUE: Should we try to handle "message/lang" here too?
592                 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
593
594                 if( is_object( $lang ) ) {
595                         $message = $lang->getMessage( $key );
596                 } else {
597                         $message = false;
598                 }
599         }
600
601         return $message;
602 }
603
604 /**
605  * Replace message parameter keys on the given formatted output.
606  *
607  * @param string $message
608  * @param array $args
609  * @return string
610  * @private
611  */
612 function wfMsgReplaceArgs( $message, $args ) {
613         # Fix windows line-endings
614         # Some messages are split with explode("\n", $msg)
615         $message = str_replace( "\r", '', $message );
616
617         // Replace arguments
618         if ( count( $args ) ) {
619                 if ( is_array( $args[0] ) ) {
620                         $args = array_values( $args[0] );
621                 }
622                 $replacementKeys = array();
623                 foreach( $args as $n => $param ) {
624                         $replacementKeys['$' . ($n + 1)] = $param;
625                 }
626                 $message = strtr( $message, $replacementKeys );
627         }
628
629         return $message;
630 }
631
632 /**
633  * Return an HTML-escaped version of a message.
634  * Parameter replacements, if any, are done *after* the HTML-escaping,
635  * so parameters may contain HTML (eg links or form controls). Be sure
636  * to pre-escape them if you really do want plaintext, or just wrap
637  * the whole thing in htmlspecialchars().
638  *
639  * @param string $key
640  * @param string ... parameters
641  * @return string
642  */
643 function wfMsgHtml( $key ) {
644         $args = func_get_args();
645         array_shift( $args );
646         return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
647 }
648
649 /**
650  * Return an HTML version of message
651  * Parameter replacements, if any, are done *after* parsing the wiki-text message,
652  * so parameters may contain HTML (eg links or form controls). Be sure
653  * to pre-escape them if you really do want plaintext, or just wrap
654  * the whole thing in htmlspecialchars().
655  *
656  * @param string $key
657  * @param string ... parameters
658  * @return string
659  */
660 function wfMsgWikiHtml( $key ) {
661         global $wgOut;
662         $args = func_get_args();
663         array_shift( $args );
664         return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
665 }
666
667 /**
668  * Returns message in the requested format
669  * @param string $key Key of the message
670  * @param array $options Processing rules.  Can take the following options:
671  *   <i>parse</i>: parses wikitext to html
672  *   <i>parseinline</i>: parses wikitext to html and removes the surrounding
673  *       p's added by parser or tidy
674  *   <i>escape</i>: filters message through htmlspecialchars
675  *   <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
676  *   <i>replaceafter</i>: parameters are substituted after parsing or escaping
677  *   <i>parsemag</i>: transform the message using magic phrases
678  *   <i>content</i>: fetch message for content language instead of interface
679  * Also can accept a single associative argument, of the form 'language' => 'xx':
680  *   <i>language</i>: Language object or language code to fetch message for
681  *       (overriden by <i>content</i>), its behaviour with parser, parseinline
682  *       and parsemag is undefined.
683  * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
684  */
685 function wfMsgExt( $key, $options ) {
686         global $wgOut;
687
688         $args = func_get_args();
689         array_shift( $args );
690         array_shift( $args );
691         $options = (array)$options;
692
693         foreach( $options as $arrayKey => $option ) {
694                 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
695                         # An unknown index, neither numeric nor "language"
696                         trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING );
697                 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
698                 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
699                 'replaceafter', 'parsemag', 'content' ) ) ) {
700                         # A numeric index with unknown value
701                         trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING );
702                 }
703         }
704
705         if( in_array('content', $options, true ) ) {
706                 $forContent = true;
707                 $langCode = true;
708         } elseif( array_key_exists('language', $options) ) {
709                 $forContent = false;
710                 $langCode = wfGetLangObj( $options['language'] );
711         } else {
712                 $forContent = false;
713                 $langCode = false;
714         }
715
716         $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
717
718         if( !in_array('replaceafter', $options, true ) ) {
719                 $string = wfMsgReplaceArgs( $string, $args );
720         }
721
722         if( in_array('parse', $options, true ) ) {
723                 $string = $wgOut->parse( $string, true, !$forContent );
724         } elseif ( in_array('parseinline', $options, true ) ) {
725                 $string = $wgOut->parse( $string, true, !$forContent );
726                 $m = array();
727                 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
728                         $string = $m[1];
729                 }
730         } elseif ( in_array('parsemag', $options, true ) ) {
731                 global $wgMessageCache;
732                 if ( isset( $wgMessageCache ) ) {
733                         $string = $wgMessageCache->transform( $string,
734                                 !$forContent,
735                                 is_object( $langCode ) ? $langCode : null );
736                 }
737         }
738
739         if ( in_array('escape', $options, true ) ) {
740                 $string = htmlspecialchars ( $string );
741         } elseif ( in_array( 'escapenoentities', $options, true  ) ) {
742                 $string = Sanitizer::escapeHtmlAllowEntities( $string );
743         }
744
745         if( in_array('replaceafter', $options, true ) ) {
746                 $string = wfMsgReplaceArgs( $string, $args );
747         }
748
749         return $string;
750 }
751
752
753 /**
754  * Just like exit() but makes a note of it.
755  * Commits open transactions except if the error parameter is set
756  *
757  * @deprecated Please return control to the caller or throw an exception
758  */
759 function wfAbruptExit( $error = false ){
760         static $called = false;
761         if ( $called ){
762                 exit( -1 );
763         }
764         $called = true;
765
766         $bt = wfDebugBacktrace();
767         if( $bt ) {
768                 for($i = 0; $i < count($bt) ; $i++){
769                         $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
770                         $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
771                         wfDebug("WARNING: Abrupt exit in $file at line $line\n");
772                 }
773         } else {
774                 wfDebug('WARNING: Abrupt exit\n');
775         }
776
777         wfLogProfilingData();
778
779         if ( !$error ) {
780                 wfGetLB()->closeAll();
781         }
782         exit( -1 );
783 }
784
785 /**
786  * @deprecated Please return control the caller or throw an exception
787  */
788 function wfErrorExit() {
789         wfAbruptExit( true );
790 }
791
792 /**
793  * Print a simple message and die, returning nonzero to the shell if any.
794  * Plain die() fails to return nonzero to the shell if you pass a string.
795  * @param string $msg
796  */
797 function wfDie( $msg='' ) {
798         echo $msg;
799         die( 1 );
800 }
801
802 /**
803  * Throw a debugging exception. This function previously once exited the process,
804  * but now throws an exception instead, with similar results.
805  *
806  * @param string $msg Message shown when dieing.
807  */
808 function wfDebugDieBacktrace( $msg = '' ) {
809         throw new MWException( $msg );
810 }
811
812 /**
813  * Fetch server name for use in error reporting etc.
814  * Use real server name if available, so we know which machine
815  * in a server farm generated the current page.
816  * @return string
817  */
818 function wfHostname() {
819         static $host;
820         if ( is_null( $host ) ) {
821                 if ( function_exists( 'posix_uname' ) ) {
822                         // This function not present on Windows
823                         $uname = @posix_uname();
824                 } else {
825                         $uname = false;
826                 }
827                 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
828                         $host = $uname['nodename'];
829                 } elseif ( getenv( 'COMPUTERNAME' ) ) {
830                         # Windows computer name
831                         $host = getenv( 'COMPUTERNAME' );
832                 } else {
833                         # This may be a virtual server.
834                         $host = $_SERVER['SERVER_NAME'];
835                 }
836         }
837         return $host;
838 }
839
840         /**
841          * Returns a HTML comment with the elapsed time since request.
842          * This method has no side effects.
843          * @return string
844          */
845         function wfReportTime() {
846                 global $wgRequestTime, $wgShowHostnames;
847
848                 $now = wfTime();
849                 $elapsed = $now - $wgRequestTime;
850
851                 return $wgShowHostnames
852                         ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
853                         : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
854         }
855
856 /**
857  * Safety wrapper for debug_backtrace().
858  *
859  * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
860  * murky circumstances, which may be triggered in part by stub objects
861  * or other fancy talkin'.
862  *
863  * Will return an empty array if Zend Optimizer is detected, otherwise
864  * the output from debug_backtrace() (trimmed).
865  *
866  * @return array of backtrace information
867  */
868 function wfDebugBacktrace() {
869         if( extension_loaded( 'Zend Optimizer' ) ) {
870                 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
871                 return array();
872         } else {
873                 return array_slice( debug_backtrace(), 1 );
874         }
875 }
876
877 function wfBacktrace() {
878         global $wgCommandLineMode;
879
880         if ( $wgCommandLineMode ) {
881                 $msg = '';
882         } else {
883                 $msg = "<ul>\n";
884         }
885         $backtrace = wfDebugBacktrace();
886         foreach( $backtrace as $call ) {
887                 if( isset( $call['file'] ) ) {
888                         $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
889                         $file = $f[count($f)-1];
890                 } else {
891                         $file = '-';
892                 }
893                 if( isset( $call['line'] ) ) {
894                         $line = $call['line'];
895                 } else {
896                         $line = '-';
897                 }
898                 if ( $wgCommandLineMode ) {
899                         $msg .= "$file line $line calls ";
900                 } else {
901                         $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
902                 }
903                 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
904                 $msg .= $call['function'] . '()';
905
906                 if ( $wgCommandLineMode ) {
907                         $msg .= "\n";
908                 } else {
909                         $msg .= "</li>\n";
910                 }
911         }
912         if ( $wgCommandLineMode ) {
913                 $msg .= "\n";
914         } else {
915                 $msg .= "</ul>\n";
916         }
917
918         return $msg;
919 }
920
921
922 /* Some generic result counters, pulled out of SearchEngine */
923
924
925 /**
926  * @todo document
927  */
928 function wfShowingResults( $offset, $limit ) {
929         global $wgLang;
930         return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
931 }
932
933 /**
934  * @todo document
935  */
936 function wfShowingResultsNum( $offset, $limit, $num ) {
937         global $wgLang;
938         return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
939 }
940
941 /**
942  * @todo document
943  */
944 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
945         global $wgLang;
946         $fmtLimit = $wgLang->formatNum( $limit );
947         $prev = wfMsg( 'prevn', $fmtLimit );
948         $next = wfMsg( 'nextn', $fmtLimit );
949
950         if( is_object( $link ) ) {
951                 $title =& $link;
952         } else {
953                 $title = Title::newFromText( $link );
954                 if( is_null( $title ) ) {
955                         return false;
956                 }
957         }
958
959         if ( 0 != $offset ) {
960                 $po = $offset - $limit;
961                 if ( $po < 0 ) { $po = 0; }
962                 $q = "limit={$limit}&offset={$po}";
963                 if ( '' != $query ) { $q .= '&'.$query; }
964                 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
965         } else { $plink = $prev; }
966
967         $no = $offset + $limit;
968         $q = 'limit='.$limit.'&offset='.$no;
969         if ( '' != $query ) { $q .= '&'.$query; }
970
971         if ( $atend ) {
972                 $nlink = $next;
973         } else {
974                 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
975         }
976         $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
977           wfNumLink( $offset, 50, $title, $query ) . ' | ' .
978           wfNumLink( $offset, 100, $title, $query ) . ' | ' .
979           wfNumLink( $offset, 250, $title, $query ) . ' | ' .
980           wfNumLink( $offset, 500, $title, $query );
981
982         return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
983 }
984
985 /**
986  * @todo document
987  */
988 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
989         global $wgLang;
990         if ( '' == $query ) { $q = ''; }
991         else { $q = $query.'&'; }
992         $q .= 'limit='.$limit.'&offset='.$offset;
993
994         $fmtLimit = $wgLang->formatNum( $limit );
995         $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
996         return $s;
997 }
998
999 /**
1000  * @todo document
1001  * @todo FIXME: we may want to blacklist some broken browsers
1002  *
1003  * @return bool Whereas client accept gzip compression
1004  */
1005 function wfClientAcceptsGzip() {
1006         global $wgUseGzip;
1007         if( $wgUseGzip ) {
1008                 # FIXME: we may want to blacklist some broken browsers
1009                 $m = array();
1010                 if( preg_match(
1011                         '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1012                         $_SERVER['HTTP_ACCEPT_ENCODING'],
1013                         $m ) ) {
1014                         if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1015                         wfDebug( " accepts gzip\n" );
1016                         return true;
1017                 }
1018         }
1019         return false;
1020 }
1021
1022 /**
1023  * Obtain the offset and limit values from the request string;
1024  * used in special pages
1025  *
1026  * @param $deflimit Default limit if none supplied
1027  * @param $optionname Name of a user preference to check against
1028  * @return array
1029  *
1030  */
1031 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1032         global $wgRequest;
1033         return $wgRequest->getLimitOffset( $deflimit, $optionname );
1034 }
1035
1036 /**
1037  * Escapes the given text so that it may be output using addWikiText()
1038  * without any linking, formatting, etc. making its way through. This
1039  * is achieved by substituting certain characters with HTML entities.
1040  * As required by the callers, <nowiki> is not used. It currently does
1041  * not filter out characters which have special meaning only at the
1042  * start of a line, such as "*".
1043  *
1044  * @param string $text Text to be escaped
1045  */
1046 function wfEscapeWikiText( $text ) {
1047         $text = str_replace(
1048                 array( '[',     '|',      ']',     '\'',    'ISBN ',     'RFC ',     '://',     "\n=",     '{{' ), # }}
1049                 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
1050                 htmlspecialchars($text) );
1051         return $text;
1052 }
1053
1054 /**
1055  * @todo document
1056  */
1057 function wfQuotedPrintable( $string, $charset = '' ) {
1058         # Probably incomplete; see RFC 2045
1059         if( empty( $charset ) ) {
1060                 global $wgInputEncoding;
1061                 $charset = $wgInputEncoding;
1062         }
1063         $charset = strtoupper( $charset );
1064         $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1065
1066         $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1067         $replace = $illegal . '\t ?_';
1068         if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1069         $out = "=?$charset?Q?";
1070         $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1071         $out .= '?=';
1072         return $out;
1073 }
1074
1075
1076 /**
1077  * @todo document
1078  * @return float
1079  */
1080 function wfTime() {
1081         return microtime(true);
1082 }
1083
1084 /**
1085  * Sets dest to source and returns the original value of dest
1086  * If source is NULL, it just returns the value, it doesn't set the variable
1087  */
1088 function wfSetVar( &$dest, $source ) {
1089         $temp = $dest;
1090         if ( !is_null( $source ) ) {
1091                 $dest = $source;
1092         }
1093         return $temp;
1094 }
1095
1096 /**
1097  * As for wfSetVar except setting a bit
1098  */
1099 function wfSetBit( &$dest, $bit, $state = true ) {
1100         $temp = (bool)($dest & $bit );
1101         if ( !is_null( $state ) ) {
1102                 if ( $state ) {
1103                         $dest |= $bit;
1104                 } else {
1105                         $dest &= ~$bit;
1106                 }
1107         }
1108         return $temp;
1109 }
1110
1111 /**
1112  * This function takes two arrays as input, and returns a CGI-style string, e.g.
1113  * "days=7&limit=100". Options in the first array override options in the second.
1114  * Options set to "" will not be output.
1115  */
1116 function wfArrayToCGI( $array1, $array2 = NULL )
1117 {
1118         if ( !is_null( $array2 ) ) {
1119                 $array1 = $array1 + $array2;
1120         }
1121
1122         $cgi = '';
1123         foreach ( $array1 as $key => $value ) {
1124                 if ( '' !== $value ) {
1125                         if ( '' != $cgi ) {
1126                                 $cgi .= '&';
1127                         }
1128                         if(is_array($value))
1129                         {
1130                                 $firstTime = true;
1131                                 foreach($value as $v)
1132                                 {
1133                                         $cgi .= ($firstTime ? '' : '&') .
1134                                                 urlencode( $key . '[]' ) . '=' .
1135                                                 urlencode( $v );
1136                                         $firstTime = false;
1137                                 }
1138                         }
1139                         else
1140                                 $cgi .= urlencode( $key ) . '=' .
1141                                         urlencode( $value );
1142                 }
1143         }
1144         return $cgi;
1145 }
1146
1147 /**
1148  * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1149  * its argument and returns the same string in array form.  This allows compa-
1150  * tibility with legacy functions that accept raw query strings instead of nice
1151  * arrays.  Of course, keys and values are urldecode()d.  Don't try passing in-
1152  * valid query strings, or it will explode.
1153  *
1154  * @param $query string Query string
1155  * @return array Array version of input
1156  */
1157 function wfCgiToArray( $query ) {
1158         if( isset( $query[0] ) and $query[0] == '?' ) {
1159                 $query = substr( $query, 1 );
1160         }
1161         $bits = explode( '&', $query );
1162         $ret = array();
1163         foreach( $bits as $bit ) {
1164                 if( $bit === '' ) {
1165                         continue;
1166                 }
1167                 list( $key, $value ) = explode( '=', $bit );
1168                 $key = urldecode( $key );
1169                 $value = urldecode( $value );
1170                 $ret[$key] = $value;
1171         }
1172         return $ret;
1173 }
1174
1175 /**
1176  * Append a query string to an existing URL, which may or may not already
1177  * have query string parameters already. If so, they will be combined.
1178  *
1179  * @param string $url
1180  * @param string $query
1181  * @return string
1182  */
1183 function wfAppendQuery( $url, $query ) {
1184         if( $query != '' ) {
1185                 if( false === strpos( $url, '?' ) ) {
1186                         $url .= '?';
1187                 } else {
1188                         $url .= '&';
1189                 }
1190                 $url .= $query;
1191         }
1192         return $url;
1193 }
1194
1195 /**
1196  * Expand a potentially local URL to a fully-qualified URL.
1197  * Assumes $wgServer is correct. :)
1198  * @param string $url, either fully-qualified or a local path + query
1199  * @return string Fully-qualified URL
1200  */
1201 function wfExpandUrl( $url ) {
1202         if( substr( $url, 0, 1 ) == '/' ) {
1203                 global $wgServer;
1204                 return $wgServer . $url;
1205         } else {
1206                 return $url;
1207         }
1208 }
1209
1210 /**
1211  * This is obsolete, use SquidUpdate::purge()
1212  * @deprecated
1213  */
1214 function wfPurgeSquidServers ($urlArr) {
1215         SquidUpdate::purge( $urlArr );
1216 }
1217
1218 /**
1219  * Windows-compatible version of escapeshellarg()
1220  * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1221  * function puts single quotes in regardless of OS.
1222  *
1223  * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to 
1224  * earlier distro releases of PHP)
1225  */
1226 function wfEscapeShellArg( ) {
1227         wfInitShellLocale();
1228
1229         $args = func_get_args();
1230         $first = true;
1231         $retVal = '';
1232         foreach ( $args as $arg ) {
1233                 if ( !$first ) {
1234                         $retVal .= ' ';
1235                 } else {
1236                         $first = false;
1237                 }
1238
1239                 if ( wfIsWindows() ) {
1240                         // Escaping for an MSVC-style command line parser
1241                         // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1242                         // Double the backslashes before any double quotes. Escape the double quotes.
1243                         $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1244                         $arg = '';
1245                         $delim = false;
1246                         foreach ( $tokens as $token ) {
1247                                 if ( $delim ) {
1248                                         $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1249                                 } else {
1250                                         $arg .= $token;
1251                                 }
1252                                 $delim = !$delim;
1253                         }
1254                         // Double the backslashes before the end of the string, because
1255                         // we will soon add a quote
1256                         $m = array();
1257                         if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1258                                 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1259                         }
1260
1261                         // Add surrounding quotes
1262                         $retVal .= '"' . $arg . '"';
1263                 } else {
1264                         $retVal .= escapeshellarg( $arg );
1265                 }
1266         }
1267         return $retVal;
1268 }
1269
1270 /**
1271  * wfMerge attempts to merge differences between three texts.
1272  * Returns true for a clean merge and false for failure or a conflict.
1273  */
1274 function wfMerge( $old, $mine, $yours, &$result ){
1275         global $wgDiff3;
1276
1277         # This check may also protect against code injection in
1278         # case of broken installations.
1279         if( !$wgDiff3 || !file_exists( $wgDiff3 ) ) {
1280                 wfDebug( "diff3 not found\n" );
1281                 return false;
1282         }
1283
1284         # Make temporary files
1285         $td = wfTempDir();
1286         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1287         $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1288         $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1289
1290         fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1291         fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1292         fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1293
1294         # Check for a conflict
1295         $cmd = $wgDiff3 . ' -a --overlap-only ' .
1296           wfEscapeShellArg( $mytextName ) . ' ' .
1297           wfEscapeShellArg( $oldtextName ) . ' ' .
1298           wfEscapeShellArg( $yourtextName );
1299         $handle = popen( $cmd, 'r' );
1300
1301         if( fgets( $handle, 1024 ) ){
1302                 $conflict = true;
1303         } else {
1304                 $conflict = false;
1305         }
1306         pclose( $handle );
1307
1308         # Merge differences
1309         $cmd = $wgDiff3 . ' -a -e --merge ' .
1310           wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1311         $handle = popen( $cmd, 'r' );
1312         $result = '';
1313         do {
1314                 $data = fread( $handle, 8192 );
1315                 if ( strlen( $data ) == 0 ) {
1316                         break;
1317                 }
1318                 $result .= $data;
1319         } while ( true );
1320         pclose( $handle );
1321         unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1322
1323         if ( $result === '' && $old !== '' && $conflict == false ) {
1324                 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1325                 $conflict = true;
1326         }
1327         return ! $conflict;
1328 }
1329
1330 /**
1331  * Returns unified plain-text diff of two texts.
1332  * Useful for machine processing of diffs.
1333  * @param $before string The text before the changes.
1334  * @param $after string The text after the changes.
1335  * @param $params string Command-line options for the diff command.
1336  * @return string Unified diff of $before and $after
1337  */
1338 function wfDiff( $before, $after, $params = '-u' ) {
1339         global $wgDiff;
1340
1341         # This check may also protect against code injection in
1342         # case of broken installations.
1343         if( !file_exists( $wgDiff ) ){
1344                 wfDebug( "diff executable not found\n" );
1345                 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1346                 $format = new UnifiedDiffFormatter();
1347                 return $format->format( $diffs );
1348         }
1349
1350         # Make temporary files
1351         $td = wfTempDir();
1352         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1353         $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1354
1355         fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1356         fwrite( $newtextFile, $after ); fclose( $newtextFile );
1357         
1358         // Get the diff of the two files
1359         $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1360         
1361         $h = popen( $cmd, 'r' );
1362         
1363         $diff = '';
1364         
1365         do {
1366                 $data = fread( $h, 8192 );
1367                 if ( strlen( $data ) == 0 ) {
1368                         break;
1369                 }
1370                 $diff .= $data;
1371         } while ( true );
1372         
1373         // Clean up
1374         pclose( $h );
1375         unlink( $oldtextName );
1376         unlink( $newtextName );
1377         
1378         // Kill the --- and +++ lines. They're not useful.
1379         $diff_lines = explode( "\n", $diff );
1380         if (strpos( $diff_lines[0], '---' ) === 0) {
1381                 unset($diff_lines[0]);
1382         }
1383         if (strpos( $diff_lines[1], '+++' ) === 0) {
1384                 unset($diff_lines[1]);
1385         }
1386         
1387         $diff = implode( "\n", $diff_lines );
1388         
1389         return $diff;
1390 }
1391
1392 /**
1393  * A wrapper around the PHP function var_export().
1394  * Either print it or add it to the regular output ($wgOut).
1395  *
1396  * @param $var A PHP variable to dump.
1397  */
1398 function wfVarDump( $var ) {
1399         global $wgOut;
1400         $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1401         if ( headers_sent() || !@is_object( $wgOut ) ) {
1402                 print $s;
1403         } else {
1404                 $wgOut->addHTML( $s );
1405         }
1406 }
1407
1408 /**
1409  * Provide a simple HTTP error.
1410  */
1411 function wfHttpError( $code, $label, $desc ) {
1412         global $wgOut;
1413         $wgOut->disable();
1414         header( "HTTP/1.0 $code $label" );
1415         header( "Status: $code $label" );
1416         $wgOut->sendCacheControl();
1417
1418         header( 'Content-type: text/html; charset=utf-8' );
1419         print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1420                 "<html><head><title>" .
1421                 htmlspecialchars( $label ) .
1422                 "</title></head><body><h1>" .
1423                 htmlspecialchars( $label ) .
1424                 "</h1><p>" .
1425                 nl2br( htmlspecialchars( $desc ) ) .
1426                 "</p></body></html>\n";
1427 }
1428
1429 /**
1430  * Clear away any user-level output buffers, discarding contents.
1431  *
1432  * Suitable for 'starting afresh', for instance when streaming
1433  * relatively large amounts of data without buffering, or wanting to
1434  * output image files without ob_gzhandler's compression.
1435  *
1436  * The optional $resetGzipEncoding parameter controls suppression of
1437  * the Content-Encoding header sent by ob_gzhandler; by default it
1438  * is left. See comments for wfClearOutputBuffers() for why it would
1439  * be used.
1440  *
1441  * Note that some PHP configuration options may add output buffer
1442  * layers which cannot be removed; these are left in place.
1443  *
1444  * @param bool $resetGzipEncoding
1445  */
1446 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1447         if( $resetGzipEncoding ) {
1448                 // Suppress Content-Encoding and Content-Length
1449                 // headers from 1.10+s wfOutputHandler
1450                 global $wgDisableOutputCompression;
1451                 $wgDisableOutputCompression = true;
1452         }
1453         while( $status = ob_get_status() ) {
1454                 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1455                         // Probably from zlib.output_compression or other
1456                         // PHP-internal setting which can't be removed.
1457                         //
1458                         // Give up, and hope the result doesn't break
1459                         // output behavior.
1460                         break;
1461                 }
1462                 if( !ob_end_clean() ) {
1463                         // Could not remove output buffer handler; abort now
1464                         // to avoid getting in some kind of infinite loop.
1465                         break;
1466                 }
1467                 if( $resetGzipEncoding ) {
1468                         if( $status['name'] == 'ob_gzhandler' ) {
1469                                 // Reset the 'Content-Encoding' field set by this handler
1470                                 // so we can start fresh.
1471                                 header( 'Content-Encoding:' );
1472                                 break;
1473                         }
1474                 }
1475         }
1476 }
1477
1478 /**
1479  * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1480  *
1481  * Clear away output buffers, but keep the Content-Encoding header
1482  * produced by ob_gzhandler, if any.
1483  *
1484  * This should be used for HTTP 304 responses, where you need to
1485  * preserve the Content-Encoding header of the real result, but
1486  * also need to suppress the output of ob_gzhandler to keep to spec
1487  * and avoid breaking Firefox in rare cases where the headers and
1488  * body are broken over two packets.
1489  */
1490 function wfClearOutputBuffers() {
1491         wfResetOutputBuffers( false );
1492 }
1493
1494 /**
1495  * Converts an Accept-* header into an array mapping string values to quality
1496  * factors
1497  */
1498 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1499         # No arg means accept anything (per HTTP spec)
1500         if( !$accept ) {
1501                 return array( $def => 1.0 );
1502         }
1503
1504         $prefs = array();
1505
1506         $parts = explode( ',', $accept );
1507
1508         foreach( $parts as $part ) {
1509                 # FIXME: doesn't deal with params like 'text/html; level=1'
1510                 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1511                 $match = array();
1512                 if( !isset( $qpart ) ) {
1513                         $prefs[$value] = 1.0;
1514                 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1515                         $prefs[$value] = floatval($match[1]);
1516                 }
1517         }
1518
1519         return $prefs;
1520 }
1521
1522 /**
1523  * Checks if a given MIME type matches any of the keys in the given
1524  * array. Basic wildcards are accepted in the array keys.
1525  *
1526  * Returns the matching MIME type (or wildcard) if a match, otherwise
1527  * NULL if no match.
1528  *
1529  * @param string $type
1530  * @param array $avail
1531  * @return string
1532  * @private
1533  */
1534 function mimeTypeMatch( $type, $avail ) {
1535         if( array_key_exists($type, $avail) ) {
1536                 return $type;
1537         } else {
1538                 $parts = explode( '/', $type );
1539                 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1540                         return $parts[0] . '/*';
1541                 } elseif( array_key_exists( '*/*', $avail ) ) {
1542                         return '*/*';
1543                 } else {
1544                         return NULL;
1545                 }
1546         }
1547 }
1548
1549 /**
1550  * Returns the 'best' match between a client's requested internet media types
1551  * and the server's list of available types. Each list should be an associative
1552  * array of type to preference (preference is a float between 0.0 and 1.0).
1553  * Wildcards in the types are acceptable.
1554  *
1555  * @param array $cprefs Client's acceptable type list
1556  * @param array $sprefs Server's offered types
1557  * @return string
1558  *
1559  * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1560  * XXX: generalize to negotiate other stuff
1561  */
1562 function wfNegotiateType( $cprefs, $sprefs ) {
1563         $combine = array();
1564
1565         foreach( array_keys($sprefs) as $type ) {
1566                 $parts = explode( '/', $type );
1567                 if( $parts[1] != '*' ) {
1568                         $ckey = mimeTypeMatch( $type, $cprefs );
1569                         if( $ckey ) {
1570                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1571                         }
1572                 }
1573         }
1574
1575         foreach( array_keys( $cprefs ) as $type ) {
1576                 $parts = explode( '/', $type );
1577                 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1578                         $skey = mimeTypeMatch( $type, $sprefs );
1579                         if( $skey ) {
1580                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1581                         }
1582                 }
1583         }
1584
1585         $bestq = 0;
1586         $besttype = NULL;
1587
1588         foreach( array_keys( $combine ) as $type ) {
1589                 if( $combine[$type] > $bestq ) {
1590                         $besttype = $type;
1591                         $bestq = $combine[$type];
1592                 }
1593         }
1594
1595         return $besttype;
1596 }
1597
1598 /**
1599  * Array lookup
1600  * Returns an array where the values in the first array are replaced by the
1601  * values in the second array with the corresponding keys
1602  *
1603  * @return array
1604  */
1605 function wfArrayLookup( $a, $b ) {
1606         return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1607 }
1608
1609 /**
1610  * Convenience function; returns MediaWiki timestamp for the present time.
1611  * @return string
1612  */
1613 function wfTimestampNow() {
1614         # return NOW
1615         return wfTimestamp( TS_MW, time() );
1616 }
1617
1618 /**
1619  * Reference-counted warning suppression
1620  */
1621 function wfSuppressWarnings( $end = false ) {
1622         static $suppressCount = 0;
1623         static $originalLevel = false;
1624
1625         if ( $end ) {
1626                 if ( $suppressCount ) {
1627                         --$suppressCount;
1628                         if ( !$suppressCount ) {
1629                                 error_reporting( $originalLevel );
1630                         }
1631                 }
1632         } else {
1633                 if ( !$suppressCount ) {
1634                         $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1635                 }
1636                 ++$suppressCount;
1637         }
1638 }
1639
1640 /**
1641  * Restore error level to previous value
1642  */
1643 function wfRestoreWarnings() {
1644         wfSuppressWarnings( true );
1645 }
1646
1647 # Autodetect, convert and provide timestamps of various types
1648
1649 /**
1650  * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1651  */
1652 define('TS_UNIX', 0);
1653
1654 /**
1655  * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1656  */
1657 define('TS_MW', 1);
1658
1659 /**
1660  * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1661  */
1662 define('TS_DB', 2);
1663
1664 /**
1665  * RFC 2822 format, for E-mail and HTTP headers
1666  */
1667 define('TS_RFC2822', 3);
1668
1669 /**
1670  * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1671  *
1672  * This is used by Special:Export
1673  */
1674 define('TS_ISO_8601', 4);
1675
1676 /**
1677  * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1678  *
1679  * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1680  *       DateTime tag and page 36 for the DateTimeOriginal and
1681  *       DateTimeDigitized tags.
1682  */
1683 define('TS_EXIF', 5);
1684
1685 /**
1686  * Oracle format time.
1687  */
1688 define('TS_ORACLE', 6);
1689
1690 /**
1691  * Postgres format time.
1692  */
1693 define('TS_POSTGRES', 7);
1694
1695 /**
1696  * @param mixed $outputtype A timestamp in one of the supported formats, the
1697  *                          function will autodetect which format is supplied
1698  *                          and act accordingly.
1699  * @return string Time in the format specified in $outputtype
1700  */
1701 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1702         $uts = 0;
1703         $da = array();
1704         if ($ts==0) {
1705                 $uts=time();
1706         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1707                 # TS_DB
1708         } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1709                 # TS_EXIF
1710         } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1711                 # TS_MW
1712         } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1713                 # TS_UNIX
1714                 $uts = $ts;
1715         } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1716                 # TS_ORACLE
1717                 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1718                                 str_replace("+00:00", "UTC", $ts)));
1719         } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1720                 # TS_ISO_8601
1721         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1722                 # TS_POSTGRES
1723         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1724                 # TS_POSTGRES
1725         } else {
1726                 # Bogus value; fall back to the epoch...
1727                 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1728                 $uts = 0;
1729         }
1730
1731         if (count( $da ) ) {
1732                 // Warning! gmmktime() acts oddly if the month or day is set to 0
1733                 // We may want to handle that explicitly at some point
1734                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1735                         (int)$da[2],(int)$da[3],(int)$da[1]);
1736         }
1737
1738         switch($outputtype) {
1739                 case TS_UNIX:
1740                         return $uts;
1741                 case TS_MW:
1742                         return gmdate( 'YmdHis', $uts );
1743                 case TS_DB:
1744                         return gmdate( 'Y-m-d H:i:s', $uts );
1745                 case TS_ISO_8601:
1746                         return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1747                 // This shouldn't ever be used, but is included for completeness
1748                 case TS_EXIF:
1749                         return gmdate(  'Y:m:d H:i:s', $uts );
1750                 case TS_RFC2822:
1751                         return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1752                 case TS_ORACLE:
1753                         return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1754                 case TS_POSTGRES:
1755                         return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1756                 default:
1757                         throw new MWException( 'wfTimestamp() called with illegal output type.');
1758         }
1759 }
1760
1761 /**
1762  * Return a formatted timestamp, or null if input is null.
1763  * For dealing with nullable timestamp columns in the database.
1764  * @param int $outputtype
1765  * @param string $ts
1766  * @return string
1767  */
1768 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1769         if( is_null( $ts ) ) {
1770                 return null;
1771         } else {
1772                 return wfTimestamp( $outputtype, $ts );
1773         }
1774 }
1775
1776 /**
1777  * Check if the operating system is Windows
1778  *
1779  * @return bool True if it's Windows, False otherwise.
1780  */
1781 function wfIsWindows() {
1782         if (substr(php_uname(), 0, 7) == 'Windows') {
1783                 return true;
1784         } else {
1785                 return false;
1786         }
1787 }
1788
1789 /**
1790  * Swap two variables
1791  */
1792 function swap( &$x, &$y ) {
1793         $z = $x;
1794         $x = $y;
1795         $y = $z;
1796 }
1797
1798 function wfGetCachedNotice( $name ) {
1799         global $wgOut, $wgRenderHashAppend, $parserMemc;
1800         $fname = 'wfGetCachedNotice';
1801         wfProfileIn( $fname );
1802
1803         $needParse = false;
1804
1805         if( $name === 'default' ) {
1806                 // special case
1807                 global $wgSiteNotice;
1808                 $notice = $wgSiteNotice;
1809                 if( empty( $notice ) ) {
1810                         wfProfileOut( $fname );
1811                         return false;
1812                 }
1813         } else {
1814                 $notice = wfMsgForContentNoTrans( $name );
1815                 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1816                         wfProfileOut( $fname );
1817                         return( false );
1818                 }
1819         }
1820
1821         // Use the extra hash appender to let eg SSL variants separately cache.
1822         $key = wfMemcKey( $name . $wgRenderHashAppend );
1823         $cachedNotice = $parserMemc->get( $key );
1824         if( is_array( $cachedNotice ) ) {
1825                 if( md5( $notice ) == $cachedNotice['hash'] ) {
1826                         $notice = $cachedNotice['html'];
1827                 } else {
1828                         $needParse = true;
1829                 }
1830         } else {
1831                 $needParse = true;
1832         }
1833
1834         if( $needParse ) {
1835                 if( is_object( $wgOut ) ) {
1836                         $parsed = $wgOut->parse( $notice );
1837                         $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1838                         $notice = $parsed;
1839                 } else {
1840                         wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1841                         $notice = '';
1842                 }
1843         }
1844
1845         wfProfileOut( $fname );
1846         return $notice;
1847 }
1848
1849 function wfGetNamespaceNotice() {
1850         global $wgTitle;
1851
1852         # Paranoia
1853         if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1854                 return "";
1855
1856         $fname = 'wfGetNamespaceNotice';
1857         wfProfileIn( $fname );
1858
1859         $key = "namespacenotice-" . $wgTitle->getNsText();
1860         $namespaceNotice = wfGetCachedNotice( $key );
1861         if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1862                  $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1863         } else {
1864                 $namespaceNotice = "";
1865         }
1866
1867         wfProfileOut( $fname );
1868         return $namespaceNotice;
1869 }
1870
1871 function wfGetSiteNotice() {
1872         global $wgUser, $wgSiteNotice;
1873         $fname = 'wfGetSiteNotice';
1874         wfProfileIn( $fname );
1875         $siteNotice = '';
1876
1877         if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1878                 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1879                         $siteNotice = wfGetCachedNotice( 'sitenotice' );
1880                 } else {
1881                         $anonNotice = wfGetCachedNotice( 'anonnotice' );
1882                         if( !$anonNotice ) {
1883                                 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1884                         } else {
1885                                 $siteNotice = $anonNotice;
1886                         }
1887                 }
1888                 if( !$siteNotice ) {
1889                         $siteNotice = wfGetCachedNotice( 'default' );
1890                 }
1891         }
1892
1893         wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1894         wfProfileOut( $fname );
1895         return $siteNotice;
1896 }
1897
1898 /**
1899  * BC wrapper for MimeMagic::singleton()
1900  * @deprecated
1901  */
1902 function &wfGetMimeMagic() {
1903         return MimeMagic::singleton();
1904 }
1905
1906 /**
1907  * Tries to get the system directory for temporary files.
1908  * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1909  * and if none are set /tmp is returned as the generic Unix default.
1910  *
1911  * NOTE: When possible, use the tempfile() function to create temporary
1912  * files to avoid race conditions on file creation, etc.
1913  *
1914  * @return string
1915  */
1916 function wfTempDir() {
1917         foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1918                 $tmp = getenv( $var );
1919                 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1920                         return $tmp;
1921                 }
1922         }
1923         # Hope this is Unix of some kind!
1924         return '/tmp';
1925 }
1926
1927 /**
1928  * Make directory, and make all parent directories if they don't exist
1929  * 
1930  * @param string $dir Full path to directory to create
1931  * @param int $mode Chmod value to use, default is $wgDirectoryMode
1932  * @return bool
1933  */
1934 function wfMkdirParents( $dir, $mode = null ) {
1935         global $wgDirectoryMode;
1936
1937         if( strval( $dir ) === '' || file_exists( $dir ) )
1938                 return true;
1939
1940         if ( is_null( $mode ) )
1941                 $mode = $wgDirectoryMode;
1942
1943         return mkdir( $dir, $mode, true );  // PHP5 <3
1944 }
1945
1946 /**
1947  * Increment a statistics counter
1948  */
1949 function wfIncrStats( $key ) {
1950         global $wgStatsMethod;
1951
1952         if( $wgStatsMethod == 'udp' ) {
1953                 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1954                 static $socket;
1955                 if (!$socket) {
1956                         $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1957                         $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1958                         socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1959                 }
1960                 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1961                 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1962         } elseif( $wgStatsMethod == 'cache' ) {
1963                 global $wgMemc;
1964                 $key = wfMemcKey( 'stats', $key );
1965                 if ( is_null( $wgMemc->incr( $key ) ) ) {
1966                         $wgMemc->add( $key, 1 );
1967                 }
1968         } else {
1969                 // Disabled
1970         }
1971 }
1972
1973 /**
1974  * @param mixed $nr The number to format
1975  * @param int $acc The number of digits after the decimal point, default 2
1976  * @param bool $round Whether or not to round the value, default true
1977  * @return float
1978  */
1979 function wfPercent( $nr, $acc = 2, $round = true ) {
1980         $ret = sprintf( "%.${acc}f", $nr );
1981         return $round ? round( $ret, $acc ) . '%' : "$ret%";
1982 }
1983
1984 /**
1985  * Encrypt a username/password.
1986  *
1987  * @param string $userid ID of the user
1988  * @param string $password Password of the user
1989  * @return string Hashed password
1990  * @deprecated Use User::crypt() or User::oldCrypt() instead
1991  */
1992 function wfEncryptPassword( $userid, $password ) {
1993         wfDeprecated(__FUNCTION__);
1994         # Just wrap around User::oldCrypt()
1995         return User::oldCrypt($password, $userid);
1996 }
1997
1998 /**
1999  * Appends to second array if $value differs from that in $default
2000  */
2001 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2002         if ( is_null( $changed ) ) {
2003                 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2004         }
2005         if ( $default[$key] !== $value ) {
2006                 $changed[$key] = $value;
2007         }
2008 }
2009
2010 /**
2011  * Since wfMsg() and co suck, they don't return false if the message key they
2012  * looked up didn't exist but a XHTML string, this function checks for the
2013  * nonexistance of messages by looking at wfMsg() output
2014  *
2015  * @param $msg      The message key looked up
2016  * @param $wfMsgOut The output of wfMsg*()
2017  * @return bool
2018  */
2019 function wfEmptyMsg( $msg, $wfMsgOut ) {
2020         return $wfMsgOut === htmlspecialchars( "<$msg>" );
2021 }
2022
2023 /**
2024  * Find out whether or not a mixed variable exists in a string
2025  *
2026  * @param mixed  needle
2027  * @param string haystack
2028  * @return bool
2029  */
2030 function in_string( $needle, $str ) {
2031         return strpos( $str, $needle ) !== false;
2032 }
2033
2034 function wfSpecialList( $page, $details ) {
2035         global $wgContLang;
2036         $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
2037         return $page . $details;
2038 }
2039
2040 /**
2041  * Returns a regular expression of url protocols
2042  *
2043  * @return string
2044  */
2045 function wfUrlProtocols() {
2046         global $wgUrlProtocols;
2047
2048         // Support old-style $wgUrlProtocols strings, for backwards compatibility
2049         // with LocalSettings files from 1.5
2050         if ( is_array( $wgUrlProtocols ) ) {
2051                 $protocols = array();
2052                 foreach ($wgUrlProtocols as $protocol)
2053                         $protocols[] = preg_quote( $protocol, '/' );
2054
2055                 return implode( '|', $protocols );
2056         } else {
2057                 return $wgUrlProtocols;
2058         }
2059 }
2060
2061 /**
2062  * Safety wrapper around ini_get() for boolean settings.
2063  * The values returned from ini_get() are pre-normalized for settings
2064  * set via php.ini or php_flag/php_admin_flag... but *not*
2065  * for those set via php_value/php_admin_value.
2066  *
2067  * It's fairly common for people to use php_value instead of php_flag,
2068  * which can leave you with an 'off' setting giving a false positive
2069  * for code that just takes the ini_get() return value as a boolean.
2070  *
2071  * To make things extra interesting, setting via php_value accepts
2072  * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2073  * Unrecognized values go false... again opposite PHP's own coercion
2074  * from string to bool.
2075  *
2076  * Luckily, 'properly' set settings will always come back as '0' or '1',
2077  * so we only have to worry about them and the 'improper' settings.
2078  *
2079  * I frickin' hate PHP... :P
2080  *
2081  * @param string $setting
2082  * @return bool
2083  */
2084 function wfIniGetBool( $setting ) {
2085         $val = ini_get( $setting );
2086         // 'on' and 'true' can't have whitespace around them, but '1' can.
2087         return strtolower( $val ) == 'on'
2088                 || strtolower( $val ) == 'true'
2089                 || strtolower( $val ) == 'yes'
2090                 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2091 }
2092
2093 /**
2094  * Execute a shell command, with time and memory limits mirrored from the PHP
2095  * configuration if supported.
2096  * @param $cmd Command line, properly escaped for shell.
2097  * @param &$retval optional, will receive the program's exit code.
2098  *                 (non-zero is usually failure)
2099  * @return collected stdout as a string (trailing newlines stripped)
2100  */
2101 function wfShellExec( $cmd, &$retval=null ) {
2102         global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2103
2104         if( wfIniGetBool( 'safe_mode' ) ) {
2105                 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2106                 $retval = 1;
2107                 return "Unable to run external programs in safe mode.";
2108         }
2109         wfInitShellLocale();
2110
2111         if ( php_uname( 's' ) == 'Linux' ) {
2112                 $time = intval( $wgMaxShellTime );
2113                 $mem = intval( $wgMaxShellMemory );
2114                 $filesize = intval( $wgMaxShellFileSize );
2115
2116                 if ( $time > 0 && $mem > 0 ) {
2117                         $script = "$IP/bin/ulimit4.sh";
2118                         if ( is_executable( $script ) ) {
2119                                 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2120                         }
2121                 }
2122         } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2123                 # This is a hack to work around PHP's flawed invocation of cmd.exe
2124                 # http://news.php.net/php.internals/21796
2125                 $cmd = '"' . $cmd . '"';
2126         }
2127         wfDebug( "wfShellExec: $cmd\n" );
2128
2129         $retval = 1; // error by default?
2130         ob_start();
2131         passthru( $cmd, $retval );
2132         $output = ob_get_contents();
2133         ob_end_clean();
2134
2135         if ( $retval == 127 ) {
2136                 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2137         }
2138         return $output;
2139 }
2140
2141 /**
2142  * Workaround for http://bugs.php.net/bug.php?id=45132
2143  * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2144  */
2145 function wfInitShellLocale() {
2146         static $done = false;
2147         if ( $done ) return;
2148         $done = true;
2149         global $wgShellLocale;
2150         if ( !wfIniGetBool( 'safe_mode' ) ) {
2151                 putenv( "LC_CTYPE=$wgShellLocale" );
2152                 setlocale( LC_CTYPE, $wgShellLocale );
2153         }
2154 }
2155
2156 /**
2157  * This function works like "use VERSION" in Perl, the program will die with a
2158  * backtrace if the current version of PHP is less than the version provided
2159  *
2160  * This is useful for extensions which due to their nature are not kept in sync
2161  * with releases, and might depend on other versions of PHP than the main code
2162  *
2163  * Note: PHP might die due to parsing errors in some cases before it ever
2164  *       manages to call this function, such is life
2165  *
2166  * @see perldoc -f use
2167  *
2168  * @param mixed $version The version to check, can be a string, an integer, or
2169  *                       a float
2170  */
2171 function wfUsePHP( $req_ver ) {
2172         $php_ver = PHP_VERSION;
2173
2174         if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2175                  throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2176 }
2177
2178 /**
2179  * This function works like "use VERSION" in Perl except it checks the version
2180  * of MediaWiki, the program will die with a backtrace if the current version
2181  * of MediaWiki is less than the version provided.
2182  *
2183  * This is useful for extensions which due to their nature are not kept in sync
2184  * with releases
2185  *
2186  * @see perldoc -f use
2187  *
2188  * @param mixed $version The version to check, can be a string, an integer, or
2189  *                       a float
2190  */
2191 function wfUseMW( $req_ver ) {
2192         global $wgVersion;
2193
2194         if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2195                 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2196 }
2197
2198 /**
2199  * @deprecated use StringUtils::escapeRegexReplacement
2200  */
2201 function wfRegexReplacement( $string ) {
2202         return StringUtils::escapeRegexReplacement( $string );
2203 }
2204
2205 /**
2206  * Return the final portion of a pathname.
2207  * Reimplemented because PHP5's basename() is buggy with multibyte text.
2208  * http://bugs.php.net/bug.php?id=33898
2209  *
2210  * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2211  * We'll consider it so always, as we don't want \s in our Unix paths either.
2212  *
2213  * @param string $path
2214  * @param string $suffix to remove if present
2215  * @return string
2216  */
2217 function wfBaseName( $path, $suffix='' ) {
2218         $encSuffix = ($suffix == '')
2219                 ? ''
2220                 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2221         $matches = array();
2222         if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2223                 return $matches[1];
2224         } else {
2225                 return '';
2226         }
2227 }
2228
2229 /**
2230  * Generate a relative path name to the given file.
2231  * May explode on non-matching case-insensitive paths,
2232  * funky symlinks, etc.
2233  *
2234  * @param string $path Absolute destination path including target filename
2235  * @param string $from Absolute source path, directory only
2236  * @return string
2237  */
2238 function wfRelativePath( $path, $from ) {
2239         // Normalize mixed input on Windows...
2240         $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2241         $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2242
2243         // Trim trailing slashes -- fix for drive root
2244         $path = rtrim( $path, DIRECTORY_SEPARATOR );
2245         $from = rtrim( $from, DIRECTORY_SEPARATOR );
2246
2247         $pieces  = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2248         $against = explode( DIRECTORY_SEPARATOR, $from );
2249
2250         if( $pieces[0] !== $against[0] ) {
2251                 // Non-matching Windows drive letters?
2252                 // Return a full path.
2253                 return $path;
2254         }
2255
2256         // Trim off common prefix
2257         while( count( $pieces ) && count( $against )
2258                 && $pieces[0] == $against[0] ) {
2259                 array_shift( $pieces );
2260                 array_shift( $against );
2261         }
2262
2263         // relative dots to bump us to the parent
2264         while( count( $against ) ) {
2265                 array_unshift( $pieces, '..' );
2266                 array_shift( $against );
2267         }
2268
2269         array_push( $pieces, wfBaseName( $path ) );
2270
2271         return implode( DIRECTORY_SEPARATOR, $pieces );
2272 }
2273
2274 /**
2275  * Backwards array plus for people who haven't bothered to read the PHP manual
2276  * XXX: will not darn your socks for you.
2277  *
2278  * @param array $array1, [$array2, [...]]
2279  * @return array
2280  */
2281 function wfArrayMerge( $array1/* ... */ ) {
2282         $args = func_get_args();
2283         $args = array_reverse( $args, true );
2284         $out = array();
2285         foreach ( $args as $arg ) {
2286                 $out += $arg;
2287         }
2288         return $out;
2289 }
2290
2291 /**
2292  * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2293  * e.g.
2294  *      wfMergeErrorArrays( 
2295  *              array( array( 'x' ) ), 
2296  *              array( array( 'x', '2' ) ), 
2297  *              array( array( 'x' ) ), 
2298  *              array( array( 'y') )
2299  *      );
2300  * returns:
2301  *              array( 
2302  *              array( 'x', '2' ),
2303  *              array( 'x' ),
2304  *              array( 'y' )
2305  *      )
2306  */
2307 function wfMergeErrorArrays(/*...*/) {
2308         $args = func_get_args();
2309         $out = array();
2310         foreach ( $args as $errors ) {
2311                 foreach ( $errors as $params ) {
2312                         $spec = implode( "\t", $params );
2313                         $out[$spec] = $params;
2314                 }
2315         }
2316         return array_values( $out );
2317 }
2318
2319 /**
2320  * Make a URL index, appropriate for the el_index field of externallinks.
2321  */
2322 function wfMakeUrlIndex( $url ) {
2323         global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2324         wfSuppressWarnings();
2325         $bits = parse_url( $url );
2326         wfRestoreWarnings();
2327         if ( !$bits ) {
2328                 return false;
2329         }
2330         // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2331         $delimiter = '';
2332         if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2333                 $delimiter = '://';
2334         } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2335                 $delimiter = ':';
2336                 // parse_url detects for news: and mailto: the host part of an url as path
2337                 // We have to correct this wrong detection
2338                 if ( isset ( $bits['path'] ) ) {
2339                         $bits['host'] = $bits['path'];
2340                         $bits['path'] = '';
2341                 }
2342         } else {
2343                 return false;
2344         }
2345
2346         // Reverse the labels in the hostname, convert to lower case
2347         // For emails reverse domainpart only
2348         if ( $bits['scheme'] == 'mailto' ) {
2349                 $mailparts = explode( '@', $bits['host'], 2 );
2350                 if ( count($mailparts) === 2 ) {
2351                         $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2352                 } else {
2353                         // No domain specified, don't mangle it
2354                         $domainpart = '';
2355                 }
2356                 $reversedHost = $domainpart . '@' . $mailparts[0];
2357         } else {
2358                 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2359         }
2360         // Add an extra dot to the end
2361         // Why? Is it in wrong place in mailto links?
2362         if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2363                 $reversedHost .= '.';
2364         }
2365         // Reconstruct the pseudo-URL
2366         $prot = $bits['scheme'];
2367         $index = "$prot$delimiter$reversedHost";
2368         // Leave out user and password. Add the port, path, query and fragment
2369         if ( isset( $bits['port'] ) )      $index .= ':' . $bits['port'];
2370         if ( isset( $bits['path'] ) ) {
2371                 $index .= $bits['path'];
2372         } else {
2373                 $index .= '/';
2374         }
2375         if ( isset( $bits['query'] ) )     $index .= '?' . $bits['query'];
2376         if ( isset( $bits['fragment'] ) )  $index .= '#' . $bits['fragment'];
2377         return $index;
2378 }
2379
2380 /**
2381  * Do any deferred updates and clear the list
2382  * TODO: This could be in Wiki.php if that class made any sense at all
2383  */
2384 function wfDoUpdates()
2385 {
2386         global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2387         foreach ( $wgDeferredUpdateList as $update ) {
2388                 $update->doUpdate();
2389         }
2390         foreach ( $wgPostCommitUpdateList as $update ) {
2391                 $update->doUpdate();
2392         }
2393         $wgDeferredUpdateList = array();
2394         $wgPostCommitUpdateList = array();
2395 }
2396
2397 /**
2398  * @deprecated use StringUtils::explodeMarkup
2399  */
2400 function wfExplodeMarkup( $separator, $text ) {
2401         return StringUtils::explodeMarkup( $separator, $text );
2402 }
2403
2404 /**
2405  * Convert an arbitrarily-long digit string from one numeric base
2406  * to another, optionally zero-padding to a minimum column width.
2407  *
2408  * Supports base 2 through 36; digit values 10-36 are represented
2409  * as lowercase letters a-z. Input is case-insensitive.
2410  *
2411  * @param $input string of digits
2412  * @param $sourceBase int 2-36
2413  * @param $destBase int 2-36
2414  * @param $pad int 1 or greater
2415  * @param $lowercase bool
2416  * @return string or false on invalid input
2417  */
2418 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2419         $input = strval( $input );
2420         if( $sourceBase < 2 ||
2421                 $sourceBase > 36 ||
2422                 $destBase < 2 ||
2423                 $destBase > 36 ||
2424                 $pad < 1 ||
2425                 $sourceBase != intval( $sourceBase ) ||
2426                 $destBase != intval( $destBase ) ||
2427                 $pad != intval( $pad ) ||
2428                 !is_string( $input ) ||
2429                 $input == '' ) {
2430                 return false;
2431         }
2432         $digitChars = ( $lowercase ) ?  '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2433         $inDigits = array();
2434         $outChars = '';
2435
2436         // Decode and validate input string
2437         $input = strtolower( $input );
2438         for( $i = 0; $i < strlen( $input ); $i++ ) {
2439                 $n = strpos( $digitChars, $input{$i} );
2440                 if( $n === false || $n > $sourceBase ) {
2441                         return false;
2442                 }
2443                 $inDigits[] = $n;
2444         }
2445
2446         // Iterate over the input, modulo-ing out an output digit
2447         // at a time until input is gone.
2448         while( count( $inDigits ) ) {
2449                 $work = 0;
2450                 $workDigits = array();
2451
2452                 // Long division...
2453                 foreach( $inDigits as $digit ) {
2454                         $work *= $sourceBase;
2455                         $work += $digit;
2456
2457                         if( $work < $destBase ) {
2458                                 // Gonna need to pull another digit.
2459                                 if( count( $workDigits ) ) {
2460                                         // Avoid zero-padding; this lets us find
2461                                         // the end of the input very easily when
2462                                         // length drops to zero.
2463                                         $workDigits[] = 0;
2464                                 }
2465                         } else {
2466                                 // Finally! Actual division!
2467                                 $workDigits[] = intval( $work / $destBase );
2468
2469                                 // Isn't it annoying that most programming languages
2470                                 // don't have a single divide-and-remainder operator,
2471                                 // even though the CPU implements it that way?
2472                                 $work = $work % $destBase;
2473                         }
2474                 }
2475
2476                 // All that division leaves us with a remainder,
2477                 // which is conveniently our next output digit.
2478                 $outChars .= $digitChars[$work];
2479
2480                 // And we continue!
2481                 $inDigits = $workDigits;
2482         }
2483
2484         while( strlen( $outChars ) < $pad ) {
2485                 $outChars .= '0';
2486         }
2487
2488         return strrev( $outChars );
2489 }
2490
2491 /**
2492  * Create an object with a given name and an array of construct parameters
2493  * @param string $name
2494  * @param array $p parameters
2495  */
2496 function wfCreateObject( $name, $p ){
2497         $p = array_values( $p );
2498         switch ( count( $p ) ) {
2499                 case 0:
2500                         return new $name;
2501                 case 1:
2502                         return new $name( $p[0] );
2503                 case 2:
2504                         return new $name( $p[0], $p[1] );
2505                 case 3:
2506                         return new $name( $p[0], $p[1], $p[2] );
2507                 case 4:
2508                         return new $name( $p[0], $p[1], $p[2], $p[3] );
2509                 case 5:
2510                         return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2511                 case 6:
2512                         return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2513                 default:
2514                         throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2515         }
2516 }
2517
2518 /**
2519  * Alias for modularized function
2520  * @deprecated Use Http::get() instead
2521  */
2522 function wfGetHTTP( $url, $timeout = 'default' ) {
2523         wfDeprecated(__FUNCTION__);
2524         return Http::get( $url, $timeout );
2525 }
2526
2527 /**
2528  * Alias for modularized function
2529  * @deprecated Use Http::isLocalURL() instead
2530  */
2531 function wfIsLocalURL( $url ) {
2532         wfDeprecated(__FUNCTION__);
2533         return Http::isLocalURL( $url );
2534 }
2535
2536 function wfHttpOnlySafe() {
2537         global $wgHttpOnlyBlacklist;
2538         if( !version_compare("5.2", PHP_VERSION, "<") )
2539                 return false;
2540
2541         if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2542                 foreach( $wgHttpOnlyBlacklist as $regex ) {
2543                         if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2544                                 return false;
2545                         }
2546                 }
2547         }
2548
2549         return true;
2550 }
2551
2552 /**
2553  * Initialise php session
2554  */
2555 function wfSetupSession() {
2556         global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2557         if( $wgSessionsInMemcached ) {
2558                 require_once( 'MemcachedSessions.php' );
2559         } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2560                 # If it's left on 'user' or another setting from another
2561                 # application, it will end up failing. Try to recover.
2562                 ini_set ( 'session.save_handler', 'files' );
2563         }
2564         $httpOnlySafe = wfHttpOnlySafe();
2565         wfDebugLog( 'cookie',
2566                 'session_set_cookie_params: "' . implode( '", "',
2567                         array(
2568                                 0,
2569                                 $wgCookiePath,
2570                                 $wgCookieDomain,
2571                                 $wgCookieSecure,
2572                                 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2573         if( $httpOnlySafe && $wgCookieHttpOnly ) {
2574                 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2575         } else {
2576                 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2577                 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2578         }
2579         session_cache_limiter( 'private, must-revalidate' );
2580         wfSuppressWarnings();
2581         session_start();
2582         wfRestoreWarnings();
2583 }
2584
2585 /**
2586  * Get an object from the precompiled serialized directory
2587  *
2588  * @return mixed The variable on success, false on failure
2589  */
2590 function wfGetPrecompiledData( $name ) {
2591         global $IP;
2592
2593         $file = "$IP/serialized/$name";
2594         if ( file_exists( $file ) ) {
2595                 $blob = file_get_contents( $file );
2596                 if ( $blob ) {
2597                         return unserialize( $blob );
2598                 }
2599         }
2600         return false;
2601 }
2602
2603 function wfGetCaller( $level = 2 ) {
2604         $backtrace = wfDebugBacktrace();
2605         if ( isset( $backtrace[$level] ) ) {
2606                 return wfFormatStackFrame($backtrace[$level]);
2607         } else {
2608                 $caller = 'unknown';
2609         }
2610         return $caller;
2611 }
2612
2613 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2614 function wfGetAllCallers() {
2615         return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2616 }
2617
2618 /** Return a string representation of frame */
2619 function wfFormatStackFrame($frame) {
2620         return isset( $frame["class"] )?
2621                 $frame["class"]."::".$frame["function"]:
2622                 $frame["function"];
2623 }
2624
2625 /**
2626  * Get a cache key
2627  */
2628 function wfMemcKey( /*... */ ) {
2629         $args = func_get_args();
2630         $key = wfWikiID() . ':' . implode( ':', $args );
2631         return $key;
2632 }
2633
2634 /**
2635  * Get a cache key for a foreign DB
2636  */
2637 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2638         $args = array_slice( func_get_args(), 2 );
2639         if ( $prefix ) {
2640                 $key = "$db-$prefix:" . implode( ':', $args );
2641         } else {
2642                 $key = $db . ':' . implode( ':', $args );
2643         }
2644         return $key;
2645 }
2646
2647 /**
2648  * Get an ASCII string identifying this wiki
2649  * This is used as a prefix in memcached keys
2650  */
2651 function wfWikiID( $db = null ) {
2652         if( $db instanceof Database ) {
2653                 return $db->getWikiID();
2654         } else {
2655         global $wgDBprefix, $wgDBname;
2656                 if ( $wgDBprefix ) {
2657                         return "$wgDBname-$wgDBprefix";
2658                 } else {
2659                         return $wgDBname;
2660                 }
2661         }
2662 }
2663
2664 /**
2665  * Split a wiki ID into DB name and table prefix
2666  */
2667 function wfSplitWikiID( $wiki ) {
2668         $bits = explode( '-', $wiki, 2 );
2669         if ( count( $bits ) < 2 ) {
2670                 $bits[] = '';
2671         }
2672         return $bits;
2673 }
2674
2675 /*
2676  * Get a Database object.
2677  * @param integer $db Index of the connection to get. May be DB_MASTER for the
2678  *                master (for write queries), DB_SLAVE for potentially lagged
2679  *                read queries, or an integer >= 0 for a particular server.
2680  *
2681  * @param mixed $groups Query groups. An array of group names that this query
2682  *              belongs to. May contain a single string if the query is only
2683  *              in one group.
2684  *
2685  * @param string $wiki The wiki ID, or false for the current wiki
2686  *
2687  * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2688  * will always return the same object, unless the underlying connection or load
2689  * balancer is manually destroyed.
2690  */
2691 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2692         return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2693 }
2694
2695 /**
2696  * Get a load balancer object.
2697  *
2698  * @param array $groups List of query groups
2699  * @param string $wiki Wiki ID, or false for the current wiki
2700  * @return LoadBalancer
2701  */
2702 function wfGetLB( $wiki = false ) {
2703         return wfGetLBFactory()->getMainLB( $wiki );
2704 }
2705
2706 /**
2707  * Get the load balancer factory object
2708  */
2709 function &wfGetLBFactory() {
2710         return LBFactory::singleton();
2711 }
2712
2713 /**
2714  * Find a file.
2715  * Shortcut for RepoGroup::singleton()->findFile()
2716  * @param mixed $title Title object or string. May be interwiki.
2717  * @param mixed $time Requested time for an archived image, or false for the
2718  *                    current version. An image object will be returned which
2719  *                    was created at the specified time.
2720  * @param mixed $flags FileRepo::FIND_ flags
2721  * @param boolean $bypass Bypass the file cache even if it could be used
2722  * @return File, or false if the file does not exist
2723  */
2724 function wfFindFile( $title, $time = false, $flags = 0, $bypass = false ) {
2725         if( !$time && !$flags && !$bypass ) {
2726                 return FileCache::singleton()->findFile( $title );
2727         } else {
2728                 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2729         }
2730 }
2731
2732 /**
2733  * Get an object referring to a locally registered file.
2734  * Returns a valid placeholder object if the file does not exist.
2735  */
2736 function wfLocalFile( $title ) {
2737         return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2738 }
2739
2740 /**
2741  * Should low-performance queries be disabled?
2742  *
2743  * @return bool
2744  */
2745 function wfQueriesMustScale() {
2746         global $wgMiserMode;
2747         return $wgMiserMode
2748                 || ( SiteStats::pages() > 100000
2749                 && SiteStats::edits() > 1000000
2750                 && SiteStats::users() > 10000 );
2751 }
2752
2753 /**
2754  * Get the path to a specified script file, respecting file
2755  * extensions; this is a wrapper around $wgScriptExtension etc.
2756  *
2757  * @param string $script Script filename, sans extension
2758  * @return string
2759  */
2760 function wfScript( $script = 'index' ) {
2761         global $wgScriptPath, $wgScriptExtension;
2762         return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2763 }
2764
2765 /**
2766  * Convenience function converts boolean values into "true"
2767  * or "false" (string) values
2768  *
2769  * @param bool $value
2770  * @return string
2771  */
2772 function wfBoolToStr( $value ) {
2773         return $value ? 'true' : 'false';
2774 }
2775
2776 /**
2777  * Load an extension messages file
2778  *
2779  * @param string $extensionName Name of extension to load messages from\for.
2780  * @param string $langcode Language to load messages for, or false for default
2781  *                         behvaiour (en, content language and user language).
2782  * @since r24808 (v1.11) Using this method of loading extension messages will not work
2783  * on MediaWiki prior to that
2784  */
2785 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2786         global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2787
2788         #For recording whether extension message files have been loaded in a given language.
2789         static $loaded = array();
2790
2791         if( !array_key_exists( $extensionName, $loaded ) ) {
2792                 $loaded[$extensionName] = array();
2793         }
2794
2795         if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2796                 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2797         }
2798
2799         if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2800                 # Just do en, content language and user language.
2801                 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2802                 # Mark that they have been loaded.
2803                 $loaded[$extensionName]['en'] = true;
2804                 $loaded[$extensionName][$wgLang->getCode()] = true;
2805                 $loaded[$extensionName][$wgContLang->getCode()] = true;
2806                 # Mark that this part has been done to avoid weird if statements.
2807                 $loaded[$extensionName]['*'] = true;
2808         } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2809                 # Load messages for specified language.
2810                 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2811                 # Mark that they have been loaded.
2812                 $loaded[$extensionName][$langcode] = true;
2813         }
2814 }
2815
2816 /**
2817  * Get a platform-independent path to the null file, e.g.
2818  * /dev/null
2819  *
2820  * @return string
2821  */
2822 function wfGetNull() {
2823         return wfIsWindows()
2824                 ? 'NUL'
2825                 : '/dev/null';
2826 }
2827
2828 /**
2829  * Displays a maxlag error
2830  *
2831  * @param string $host Server that lags the most
2832  * @param int $lag Maxlag (actual)
2833  * @param int $maxLag Maxlag (requested)
2834  */
2835 function wfMaxlagError( $host, $lag, $maxLag ) {
2836         global $wgShowHostnames;
2837         header( 'HTTP/1.1 503 Service Unavailable' );
2838         header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2839         header( 'X-Database-Lag: ' . intval( $lag ) );
2840         header( 'Content-Type: text/plain' );
2841         if( $wgShowHostnames ) {
2842                 echo "Waiting for $host: $lag seconds lagged\n";
2843         } else {
2844                 echo "Waiting for a database server: $lag seconds lagged\n";
2845         }
2846 }
2847
2848 /**
2849  * Throws an E_USER_NOTICE saying that $function is deprecated
2850  * @param string $function
2851  * @return null
2852  */
2853 function wfDeprecated( $function ) {
2854         global $wgDebugLogFile;
2855         if ( !$wgDebugLogFile ) {
2856                 return;
2857         }
2858         $callers = wfDebugBacktrace();
2859         if( isset( $callers[2] ) ){
2860                 $callerfunc = $callers[2];
2861                 $callerfile = $callers[1];
2862                 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2863                         $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2864                 } else {
2865                         $file = '(internal function)';
2866                 }
2867                 $func = '';
2868                 if( isset( $callerfunc['class'] ) )
2869                         $func .= $callerfunc['class'] . '::';
2870                 $func .= @$callerfunc['function'];
2871                 $msg = "Use of $function is deprecated. Called from $func in $file";
2872         } else {
2873                 $msg = "Use of $function is deprecated.";
2874         }
2875         wfDebug( "$msg\n" );
2876 }
2877
2878 /**
2879  * Sleep until the worst slave's replication lag is less than or equal to
2880  * $maxLag, in seconds.  Use this when updating very large numbers of rows, as
2881  * in maintenance scripts, to avoid causing too much lag.  Of course, this is
2882  * a no-op if there are no slaves.
2883  *
2884  * Every time the function has to wait for a slave, it will print a message to
2885  * that effect (and then sleep for a little while), so it's probably not best
2886  * to use this outside maintenance scripts in its present form.
2887  *
2888  * @param int $maxLag
2889  * @return null
2890  */
2891 function wfWaitForSlaves( $maxLag ) {
2892         if( $maxLag ) {
2893                 $lb = wfGetLB();
2894                 list( $host, $lag ) = $lb->getMaxLag();
2895                 while( $lag > $maxLag ) {
2896                         $name = @gethostbyaddr( $host );
2897                         if( $name !== false ) {
2898                                 $host = $name;
2899                         }
2900                         print "Waiting for $host (lagged $lag seconds)...\n";
2901                         sleep($maxLag);
2902                         list( $host, $lag ) = $lb->getMaxLag();
2903                 }
2904         }
2905 }
2906
2907 /**
2908  * Output some plain text in command-line mode or in the installer (updaters.inc).
2909  * Do not use it in any other context, its behaviour is subject to change.
2910  */
2911 function wfOut( $s ) {
2912         static $lineStarted = false;
2913         global $wgCommandLineMode;
2914         if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
2915                 echo $s;
2916         } else {
2917                 echo htmlspecialchars( $s );
2918         }
2919         flush();
2920 }
2921
2922 /** Generate a random 32-character hexadecimal token.
2923  * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2924  */
2925 function wfGenerateToken( $salt = '' ) {
2926         $salt = serialize($salt);
2927
2928         return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2929 }
2930
2931 /**
2932  * Replace all invalid characters with -
2933  * @param mixed $title Filename to process
2934  */
2935 function wfStripIllegalFilenameChars( $name ) {
2936         $name = wfBaseName( $name );
2937         $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2938         return $name;
2939 }