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