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