]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/GlobalFunctions.php
MediaWiki 1.11.0
[autoinstallsdev/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 /**
12  * Some globals and requires needed
13  */
14
15 /** Total number of articles */
16 $wgNumberOfArticles = -1; # Unset
17
18 /** Total number of views */
19 $wgTotalViews = -1;
20
21 /** Total number of edits */
22 $wgTotalEdits = -1;
23
24
25 require_once dirname(__FILE__) . '/LogPage.php';
26 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
27 require_once dirname(__FILE__) . '/XmlFunctions.php';
28
29 /**
30  * Compatibility functions
31  *
32  * We more or less support PHP 5.0.x and up.
33  * Re-implementations of newer functions or functions in non-standard
34  * PHP extensions may be included here.
35  */
36 if( !function_exists('iconv') ) {
37         # iconv support is not in the default configuration and so may not be present.
38         # Assume will only ever use utf-8 and iso-8859-1.
39         # This will *not* work in all circumstances.
40         function iconv( $from, $to, $string ) {
41                 if(strcasecmp( $from, $to ) == 0) return $string;
42                 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
43                 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
44                 return $string;
45         }
46 }
47
48 # UTF-8 substr function based on a PHP manual comment
49 if ( !function_exists( 'mb_substr' ) ) {
50         function mb_substr( $str, $start ) {
51                 $ar = array();
52                 preg_match_all( '/./us', $str, $ar );
53
54                 if( func_num_args() >= 3 ) {
55                         $end = func_get_arg( 2 );
56                         return join( '', array_slice( $ar[0], $start, $end ) );
57                 } else {
58                         return join( '', array_slice( $ar[0], $start ) );
59                 }
60         }
61 }
62
63 if ( !function_exists( 'mb_strlen' ) ) {
64         /**
65          * Fallback implementation of mb_strlen, hardcoded to UTF-8.
66          * @param string $str
67          * @param string $enc optional encoding; ignored
68          * @return int
69          */
70         function mb_strlen( $str, $enc="" ) {
71                 $counts = count_chars( $str );
72                 $total = 0;
73
74                 // Count ASCII bytes
75                 for( $i = 0; $i < 0x80; $i++ ) {
76                         $total += $counts[$i];
77                 }
78
79                 // Count multibyte sequence heads
80                 for( $i = 0xc0; $i < 0xff; $i++ ) {
81                         $total += $counts[$i];
82                 }
83                 return $total;
84         }
85 }
86
87 if ( !function_exists( 'array_diff_key' ) ) {
88         /**
89          * Exists in PHP 5.1.0+
90          * Not quite compatible, two-argument version only
91          * Null values will cause problems due to this use of isset()
92          */
93         function array_diff_key( $left, $right ) {
94                 $result = $left;
95                 foreach ( $left as $key => $unused ) {
96                         if ( isset( $right[$key] ) ) {
97                                 unset( $result[$key] );
98                         }
99                 }
100                 return $result;
101         }
102 }
103
104
105 /**
106  * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
107  * PHP 5 won't let you declare a 'clone' function, even conditionally,
108  * so it has to be a wrapper with a different name.
109  */
110 function wfClone( $object ) {
111         return clone( $object );
112 }
113
114 /**
115  * Where as we got a random seed
116  */
117 $wgRandomSeeded = false;
118
119 /**
120  * Seed Mersenne Twister
121  * No-op for compatibility; only necessary in PHP < 4.2.0
122  */
123 function wfSeedRandom() {
124         /* No-op */
125 }
126
127 /**
128  * Get a random decimal value between 0 and 1, in a way
129  * not likely to give duplicate values for any realistic
130  * number of articles.
131  *
132  * @return string
133  */
134 function wfRandom() {
135         # The maximum random value is "only" 2^31-1, so get two random
136         # values to reduce the chance of dupes
137         $max = mt_getrandmax() + 1;
138         $rand = number_format( (mt_rand() * $max + mt_rand())
139                 / $max / $max, 12, '.', '' );
140         return $rand;
141 }
142
143 /**
144  * We want / and : to be included as literal characters in our title URLs.
145  * %2F in the page titles seems to fatally break for some reason.
146  *
147  * @param $s String:
148  * @return string
149 */
150 function wfUrlencode ( $s ) {
151         $s = urlencode( $s );
152         $s = preg_replace( '/%3[Aa]/', ':', $s );
153         $s = preg_replace( '/%2[Ff]/', '/', $s );
154
155         return $s;
156 }
157
158 /**
159  * Sends a line to the debug log if enabled or, optionally, to a comment in output.
160  * In normal operation this is a NOP.
161  *
162  * Controlling globals:
163  * $wgDebugLogFile - points to the log file
164  * $wgProfileOnly - if set, normal debug messages will not be recorded.
165  * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
166  * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
167  *
168  * @param $text String
169  * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
170  */
171 function wfDebug( $text, $logonly = false ) {
172         global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
173         static $recursion = 0;
174
175         # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
176         if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
177                 return;
178         }
179
180         if ( $wgDebugComments && !$logonly ) {
181                 if ( !isset( $wgOut ) ) {
182                         return;
183                 }
184                 if ( !StubObject::isRealObject( $wgOut ) ) {
185                         if ( $recursion ) {
186                                 return;
187                         }
188                         $recursion++;
189                         $wgOut->_unstub();
190                         $recursion--;
191                 }
192                 $wgOut->debug( $text );
193         }
194         if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
195                 # Strip unprintables; they can switch terminal modes when binary data
196                 # gets dumped, which is pretty annoying.
197                 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
198                 wfErrorLog( $text, $wgDebugLogFile );
199         }
200 }
201
202 /**
203  * Send a line to a supplementary debug log file, if configured, or main debug log if not.
204  * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
205  *
206  * @param $logGroup String
207  * @param $text String
208  * @param $public Bool: whether to log the event in the public log if no private
209  *                     log file is specified, (default true)
210  */
211 function wfDebugLog( $logGroup, $text, $public = true ) {
212         global $wgDebugLogGroups;
213         if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
214         if( isset( $wgDebugLogGroups[$logGroup] ) ) {
215                 $time = wfTimestamp( TS_DB );
216                 $wiki = wfWikiID();
217                 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
218         } else if ( $public === true ) {
219                 wfDebug( $text, true );
220         }
221 }
222
223 /**
224  * Log for database errors
225  * @param $text String: database error message.
226  */
227 function wfLogDBError( $text ) {
228         global $wgDBerrorLog, $wgDBname;
229         if ( $wgDBerrorLog ) {
230                 $host = trim(`hostname`);
231                 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
232                 wfErrorLog( $text, $wgDBerrorLog );
233         }
234 }
235
236 /**
237  * Log to a file without getting "file size exceeded" signals
238  */
239 function wfErrorLog( $text, $file ) {
240         wfSuppressWarnings();
241         $exists = file_exists( $file );
242         $size = $exists ? filesize( $file ) : false;
243         if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
244                 error_log( $text, 3, $file );
245         }
246         wfRestoreWarnings();
247 }
248
249 /**
250  * @todo document
251  */
252 function wfLogProfilingData() {
253         global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
254         global $wgProfiling, $wgUser;
255         if ( $wgProfiling ) {
256                 $now = wfTime();
257                 $elapsed = $now - $wgRequestTime;
258                 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
259                 $forward = '';
260                 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
261                         $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
262                 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
263                         $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
264                 if( !empty( $_SERVER['HTTP_FROM'] ) )
265                         $forward .= ' from ' . $_SERVER['HTTP_FROM'];
266                 if( $forward )
267                         $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
268                 // Don't unstub $wgUser at this late stage just for statistics purposes
269                 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
270                         $forward .= ' anon';
271                 $log = sprintf( "%s\t%04.3f\t%s\n",
272                   gmdate( 'YmdHis' ), $elapsed,
273                   urldecode( $wgRequest->getRequestURL() . $forward ) );
274                 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
275                         wfErrorLog( $log . $prof, $wgDebugLogFile );
276                 }
277         }
278 }
279
280 /**
281  * Check if the wiki read-only lock file is present. This can be used to lock
282  * off editing functions, but doesn't guarantee that the database will not be
283  * modified.
284  * @return bool
285  */
286 function wfReadOnly() {
287         global $wgReadOnlyFile, $wgReadOnly;
288
289         if ( !is_null( $wgReadOnly ) ) {
290                 return (bool)$wgReadOnly;
291         }
292         if ( '' == $wgReadOnlyFile ) {
293                 return false;
294         }
295         // Set $wgReadOnly for faster access next time
296         if ( is_file( $wgReadOnlyFile ) ) {
297                 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
298         } else {
299                 $wgReadOnly = false;
300         }
301         return (bool)$wgReadOnly;
302 }
303
304
305 /**
306  * Get a message from anywhere, for the current user language.
307  *
308  * Use wfMsgForContent() instead if the message should NOT
309  * change depending on the user preferences.
310  *
311  * Note that the message may contain HTML, and is therefore
312  * not safe for insertion anywhere. Some functions such as
313  * addWikiText will do the escaping for you. Use wfMsgHtml()
314  * if you need an escaped message.
315  *
316  * @param $key String: lookup key for the message, usually
317  *    defined in languages/Language.php
318  * 
319  * This function also takes extra optional parameters (not 
320  * shown in the function definition), which can by used to 
321  * insert variable text into the predefined message.
322  */
323 function wfMsg( $key ) {
324         $args = func_get_args();
325         array_shift( $args );
326         return wfMsgReal( $key, $args, true );
327 }
328
329 /**
330  * Same as above except doesn't transform the message
331  */
332 function wfMsgNoTrans( $key ) {
333         $args = func_get_args();
334         array_shift( $args );
335         return wfMsgReal( $key, $args, true, false, false );
336 }
337
338 /**
339  * Get a message from anywhere, for the current global language
340  * set with $wgLanguageCode.
341  *
342  * Use this if the message should NOT change  dependent on the
343  * language set in the user's preferences. This is the case for
344  * most text written into logs, as well as link targets (such as
345  * the name of the copyright policy page). Link titles, on the
346  * other hand, should be shown in the UI language.
347  *
348  * Note that MediaWiki allows users to change the user interface
349  * language in their preferences, but a single installation
350  * typically only contains content in one language.
351  *
352  * Be wary of this distinction: If you use wfMsg() where you should
353  * use wfMsgForContent(), a user of the software may have to
354  * customize over 70 messages in order to, e.g., fix a link in every
355  * possible language.
356  *
357  * @param $key String: lookup key for the message, usually
358  *    defined in languages/Language.php
359  */
360 function wfMsgForContent( $key ) {
361         global $wgForceUIMsgAsContentMsg;
362         $args = func_get_args();
363         array_shift( $args );
364         $forcontent = true;
365         if( is_array( $wgForceUIMsgAsContentMsg ) &&
366                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
367                 $forcontent = false;
368         return wfMsgReal( $key, $args, true, $forcontent );
369 }
370
371 /**
372  * Same as above except doesn't transform the message
373  */
374 function wfMsgForContentNoTrans( $key ) {
375         global $wgForceUIMsgAsContentMsg;
376         $args = func_get_args();
377         array_shift( $args );
378         $forcontent = true;
379         if( is_array( $wgForceUIMsgAsContentMsg ) &&
380                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
381                 $forcontent = false;
382         return wfMsgReal( $key, $args, true, $forcontent, false );
383 }
384
385 /**
386  * Get a message from the language file, for the UI elements
387  */
388 function wfMsgNoDB( $key ) {
389         $args = func_get_args();
390         array_shift( $args );
391         return wfMsgReal( $key, $args, false );
392 }
393
394 /**
395  * Get a message from the language file, for the content
396  */
397 function wfMsgNoDBForContent( $key ) {
398         global $wgForceUIMsgAsContentMsg;
399         $args = func_get_args();
400         array_shift( $args );
401         $forcontent = true;
402         if( is_array( $wgForceUIMsgAsContentMsg ) &&
403                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
404                 $forcontent = false;
405         return wfMsgReal( $key, $args, false, $forcontent );
406 }
407
408
409 /**
410  * Really get a message
411  * @param $key String: key to get.
412  * @param $args
413  * @param $useDB Boolean
414  * @param $transform Boolean: Whether or not to transform the message.
415  * @param $forContent Boolean
416  * @return String: the requested message.
417  */
418 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
419         $fname = 'wfMsgReal';
420         wfProfileIn( $fname );
421         $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
422         $message = wfMsgReplaceArgs( $message, $args );
423         wfProfileOut( $fname );
424         return $message;
425 }
426
427 /**
428  * This function provides the message source for messages to be edited which are *not* stored in the database.
429  * @param $key String:
430  */
431 function wfMsgWeirdKey ( $key ) {
432         $source = wfMsgGetKey( $key, false, true, false );
433         if ( wfEmptyMsg( $key, $source ) )
434                 return "";
435         else
436                 return $source;
437 }
438
439 /**
440  * Fetch a message string value, but don't replace any keys yet.
441  * @param string $key
442  * @param bool $useDB
443  * @param bool $forContent
444  * @return string
445  * @private
446  */
447 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
448         global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
449
450         /* <Vyznev> btw, is all that code in wfMsgGetKey() that check
451          * if the message cache exists of not really necessary, or is
452          * it just paranoia?
453          * <TimStarling> Vyznev: it's probably not necessary
454          * <TimStarling> I think I wrote it in an attempt to report DB
455          * connection errors properly
456          * <TimStarling> but eventually we gave up on using the
457          * message cache for that and just hard-coded the strings
458          * <TimStarling> it may have other uses, it's not mere paranoia
459          */
460
461         if ( is_object( $wgMessageCache ) )
462                 $transstat = $wgMessageCache->getTransform();
463
464         if( is_object( $wgMessageCache ) ) {
465                 if ( ! $transform )
466                         $wgMessageCache->disableTransform();
467                 $message = $wgMessageCache->get( $key, $useDB, $forContent );
468         } else {
469                 if( $forContent ) {
470                         $lang = &$wgContLang;
471                 } else {
472                         $lang = &$wgLang;
473                 }
474
475                 # MessageCache::get() does this already, Language::getMessage() doesn't
476                 # ISSUE: Should we try to handle "message/lang" here too?
477                 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
478
479                 wfSuppressWarnings();
480                 if( is_object( $lang ) ) {
481                         $message = $lang->getMessage( $key );
482                 } else {
483                         $message = false;
484                 }
485                 wfRestoreWarnings();
486
487                 if ( $transform && strstr( $message, '{{' ) !== false ) {
488                         $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
489                 }
490         }
491
492         if ( is_object( $wgMessageCache ) && ! $transform )
493                 $wgMessageCache->setTransform( $transstat );
494
495         return $message;
496 }
497
498 /**
499  * Replace message parameter keys on the given formatted output.
500  *
501  * @param string $message
502  * @param array $args
503  * @return string
504  * @private
505  */
506 function wfMsgReplaceArgs( $message, $args ) {
507         # Fix windows line-endings
508         # Some messages are split with explode("\n", $msg)
509         $message = str_replace( "\r", '', $message );
510
511         // Replace arguments
512         if ( count( $args ) ) {
513                 if ( is_array( $args[0] ) ) {
514                         foreach ( $args[0] as $key => $val ) {
515                                 $message = str_replace( '$' . $key, $val, $message );
516                         }
517                 } else {
518                         foreach( $args as $n => $param ) {
519                                 $replacementKeys['$' . ($n + 1)] = $param;
520                         }
521                         $message = strtr( $message, $replacementKeys );
522                 }
523         }
524
525         return $message;
526 }
527
528 /**
529  * Return an HTML-escaped version of a message.
530  * Parameter replacements, if any, are done *after* the HTML-escaping,
531  * so parameters may contain HTML (eg links or form controls). Be sure
532  * to pre-escape them if you really do want plaintext, or just wrap
533  * the whole thing in htmlspecialchars().
534  *
535  * @param string $key
536  * @param string ... parameters
537  * @return string
538  */
539 function wfMsgHtml( $key ) {
540         $args = func_get_args();
541         array_shift( $args );
542         return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
543 }
544
545 /**
546  * Return an HTML version of message
547  * Parameter replacements, if any, are done *after* parsing the wiki-text message,
548  * so parameters may contain HTML (eg links or form controls). Be sure
549  * to pre-escape them if you really do want plaintext, or just wrap
550  * the whole thing in htmlspecialchars().
551  *
552  * @param string $key
553  * @param string ... parameters
554  * @return string
555  */
556 function wfMsgWikiHtml( $key ) {
557         global $wgOut;
558         $args = func_get_args();
559         array_shift( $args );
560         return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
561 }
562
563 /**
564  * Returns message in the requested format
565  * @param string $key Key of the message
566  * @param array $options Processing rules:
567  *  <i>parse</i>: parses wikitext to html
568  *  <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
569  *  <i>escape</i>: filters message trough htmlspecialchars
570  *  <i>replaceafter</i>: parameters are substituted after parsing or escaping
571  *  <i>parsemag</i>: transform the message using magic phrases
572  */
573 function wfMsgExt( $key, $options ) {
574         global $wgOut, $wgParser;
575
576         $args = func_get_args();
577         array_shift( $args );
578         array_shift( $args );
579
580         if( !is_array($options) ) {
581                 $options = array($options);
582         }
583
584         $string = wfMsgGetKey( $key, true, false, false );
585
586         if( !in_array('replaceafter', $options) ) {
587                 $string = wfMsgReplaceArgs( $string, $args );
588         }
589
590         if( in_array('parse', $options) ) {
591                 $string = $wgOut->parse( $string, true, true );
592         } elseif ( in_array('parseinline', $options) ) {
593                 $string = $wgOut->parse( $string, true, true );
594                 $m = array();
595                 if( preg_match( '/^<p>(.*)\n?<\/p>$/sU', $string, $m ) ) {
596                         $string = $m[1];
597                 }
598         } elseif ( in_array('parsemag', $options) ) {
599                 global $wgMessageCache;
600                 if ( isset( $wgMessageCache ) ) {
601                         $string = $wgMessageCache->transform( $string );
602                 }
603         }
604
605         if ( in_array('escape', $options) ) {
606                 $string = htmlspecialchars ( $string );
607         }
608
609         if( in_array('replaceafter', $options) ) {
610                 $string = wfMsgReplaceArgs( $string, $args );
611         }
612
613         return $string;
614 }
615
616
617 /**
618  * Just like exit() but makes a note of it.
619  * Commits open transactions except if the error parameter is set
620  *
621  * @deprecated Please return control to the caller or throw an exception
622  */
623 function wfAbruptExit( $error = false ){
624         global $wgLoadBalancer;
625         static $called = false;
626         if ( $called ){
627                 exit( -1 );
628         }
629         $called = true;
630
631         $bt = wfDebugBacktrace();
632         if( $bt ) {
633                 for($i = 0; $i < count($bt) ; $i++){
634                         $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
635                         $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
636                         wfDebug("WARNING: Abrupt exit in $file at line $line\n");
637                 }
638         } else {
639                 wfDebug('WARNING: Abrupt exit\n');
640         }
641
642         wfLogProfilingData();
643
644         if ( !$error ) {
645                 $wgLoadBalancer->closeAll();
646         }
647         exit( -1 );
648 }
649
650 /**
651  * @deprecated Please return control the caller or throw an exception
652  */
653 function wfErrorExit() {
654         wfAbruptExit( true );
655 }
656
657 /**
658  * Print a simple message and die, returning nonzero to the shell if any.
659  * Plain die() fails to return nonzero to the shell if you pass a string.
660  * @param string $msg
661  */
662 function wfDie( $msg='' ) {
663         echo $msg;
664         die( 1 );
665 }
666
667 /**
668  * Throw a debugging exception. This function previously once exited the process, 
669  * but now throws an exception instead, with similar results.
670  *
671  * @param string $msg Message shown when dieing.
672  */
673 function wfDebugDieBacktrace( $msg = '' ) {
674         throw new MWException( $msg );
675 }
676
677 /**
678  * Fetch server name for use in error reporting etc.
679  * Use real server name if available, so we know which machine
680  * in a server farm generated the current page.
681  * @return string
682  */
683 function wfHostname() {
684         if ( function_exists( 'posix_uname' ) ) {
685                 // This function not present on Windows
686                 $uname = @posix_uname();
687         } else {
688                 $uname = false;
689         }
690         if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
691                 return $uname['nodename'];
692         } else {
693                 # This may be a virtual server.
694                 return $_SERVER['SERVER_NAME'];
695         }
696 }
697
698         /**
699          * Returns a HTML comment with the elapsed time since request.
700          * This method has no side effects.
701          * @return string
702          */
703         function wfReportTime() {
704                 global $wgRequestTime, $wgShowHostnames;
705
706                 $now = wfTime();
707                 $elapsed = $now - $wgRequestTime;
708
709                 return $wgShowHostnames
710                         ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
711                         : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
712         }
713
714 /**
715  * Safety wrapper for debug_backtrace().
716  *
717  * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
718  * murky circumstances, which may be triggered in part by stub objects
719  * or other fancy talkin'.
720  *
721  * Will return an empty array if Zend Optimizer is detected, otherwise
722  * the output from debug_backtrace() (trimmed).
723  *
724  * @return array of backtrace information
725  */
726 function wfDebugBacktrace() {
727         if( extension_loaded( 'Zend Optimizer' ) ) {
728                 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
729                 return array();
730         } else {
731                 return array_slice( debug_backtrace(), 1 );
732         }
733 }
734
735 function wfBacktrace() {
736         global $wgCommandLineMode;
737
738         if ( $wgCommandLineMode ) {
739                 $msg = '';
740         } else {
741                 $msg = "<ul>\n";
742         }
743         $backtrace = wfDebugBacktrace();
744         foreach( $backtrace as $call ) {
745                 if( isset( $call['file'] ) ) {
746                         $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
747                         $file = $f[count($f)-1];
748                 } else {
749                         $file = '-';
750                 }
751                 if( isset( $call['line'] ) ) {
752                         $line = $call['line'];
753                 } else {
754                         $line = '-';
755                 }
756                 if ( $wgCommandLineMode ) {
757                         $msg .= "$file line $line calls ";
758                 } else {
759                         $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
760                 }
761                 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
762                 $msg .= $call['function'] . '()';
763
764                 if ( $wgCommandLineMode ) {
765                         $msg .= "\n";
766                 } else {
767                         $msg .= "</li>\n";
768                 }
769         }
770         if ( $wgCommandLineMode ) {
771                 $msg .= "\n";
772         } else {
773                 $msg .= "</ul>\n";
774         }
775
776         return $msg;
777 }
778
779
780 /* Some generic result counters, pulled out of SearchEngine */
781
782
783 /**
784  * @todo document
785  */
786 function wfShowingResults( $offset, $limit ) {
787         global $wgLang;
788         return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
789 }
790
791 /**
792  * @todo document
793  */
794 function wfShowingResultsNum( $offset, $limit, $num ) {
795         global $wgLang;
796         return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
797 }
798
799 /**
800  * @todo document
801  */
802 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
803         global $wgLang;
804         $fmtLimit = $wgLang->formatNum( $limit );
805         $prev = wfMsg( 'prevn', $fmtLimit );
806         $next = wfMsg( 'nextn', $fmtLimit );
807
808         if( is_object( $link ) ) {
809                 $title =& $link;
810         } else {
811                 $title = Title::newFromText( $link );
812                 if( is_null( $title ) ) {
813                         return false;
814                 }
815         }
816
817         if ( 0 != $offset ) {
818                 $po = $offset - $limit;
819                 if ( $po < 0 ) { $po = 0; }
820                 $q = "limit={$limit}&offset={$po}";
821                 if ( '' != $query ) { $q .= '&'.$query; }
822                 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
823         } else { $plink = $prev; }
824
825         $no = $offset + $limit;
826         $q = 'limit='.$limit.'&offset='.$no;
827         if ( '' != $query ) { $q .= '&'.$query; }
828
829         if ( $atend ) {
830                 $nlink = $next;
831         } else {
832                 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
833         }
834         $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
835           wfNumLink( $offset, 50, $title, $query ) . ' | ' .
836           wfNumLink( $offset, 100, $title, $query ) . ' | ' .
837           wfNumLink( $offset, 250, $title, $query ) . ' | ' .
838           wfNumLink( $offset, 500, $title, $query );
839
840         return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
841 }
842
843 /**
844  * @todo document
845  */
846 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
847         global $wgLang;
848         if ( '' == $query ) { $q = ''; }
849         else { $q = $query.'&'; }
850         $q .= 'limit='.$limit.'&offset='.$offset;
851
852         $fmtLimit = $wgLang->formatNum( $limit );
853         $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
854         return $s;
855 }
856
857 /**
858  * @todo document
859  * @todo FIXME: we may want to blacklist some broken browsers
860  *
861  * @return bool Whereas client accept gzip compression
862  */
863 function wfClientAcceptsGzip() {
864         global $wgUseGzip;
865         if( $wgUseGzip ) {
866                 # FIXME: we may want to blacklist some broken browsers
867                 $m = array();
868                 if( preg_match(
869                         '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
870                         $_SERVER['HTTP_ACCEPT_ENCODING'],
871                         $m ) ) {
872                         if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
873                         wfDebug( " accepts gzip\n" );
874                         return true;
875                 }
876         }
877         return false;
878 }
879
880 /**
881  * Obtain the offset and limit values from the request string;
882  * used in special pages
883  *
884  * @param $deflimit Default limit if none supplied
885  * @param $optionname Name of a user preference to check against
886  * @return array
887  * 
888  */
889 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
890         global $wgRequest;
891         return $wgRequest->getLimitOffset( $deflimit, $optionname );
892 }
893
894 /**
895  * Escapes the given text so that it may be output using addWikiText()
896  * without any linking, formatting, etc. making its way through. This
897  * is achieved by substituting certain characters with HTML entities.
898  * As required by the callers, <nowiki> is not used. It currently does
899  * not filter out characters which have special meaning only at the
900  * start of a line, such as "*".
901  *
902  * @param string $text Text to be escaped
903  */
904 function wfEscapeWikiText( $text ) {
905         $text = str_replace(
906                 array( '[',     '|',      '\'',    'ISBN ',     'RFC ',     '://',     "\n=",     '{{' ),
907                 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
908                 htmlspecialchars($text) );
909         return $text;
910 }
911
912 /**
913  * @todo document
914  */
915 function wfQuotedPrintable( $string, $charset = '' ) {
916         # Probably incomplete; see RFC 2045
917         if( empty( $charset ) ) {
918                 global $wgInputEncoding;
919                 $charset = $wgInputEncoding;
920         }
921         $charset = strtoupper( $charset );
922         $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
923
924         $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
925         $replace = $illegal . '\t ?_';
926         if( !preg_match( "/[$illegal]/", $string ) ) return $string;
927         $out = "=?$charset?Q?";
928         $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
929         $out .= '?=';
930         return $out;
931 }
932
933
934 /**
935  * @todo document
936  * @return float
937  */
938 function wfTime() {
939         return microtime(true);
940 }
941
942 /**
943  * Sets dest to source and returns the original value of dest
944  * If source is NULL, it just returns the value, it doesn't set the variable
945  */
946 function wfSetVar( &$dest, $source ) {
947         $temp = $dest;
948         if ( !is_null( $source ) ) {
949                 $dest = $source;
950         }
951         return $temp;
952 }
953
954 /**
955  * As for wfSetVar except setting a bit
956  */
957 function wfSetBit( &$dest, $bit, $state = true ) {
958         $temp = (bool)($dest & $bit );
959         if ( !is_null( $state ) ) {
960                 if ( $state ) {
961                         $dest |= $bit;
962                 } else {
963                         $dest &= ~$bit;
964                 }
965         }
966         return $temp;
967 }
968
969 /**
970  * This function takes two arrays as input, and returns a CGI-style string, e.g.
971  * "days=7&limit=100". Options in the first array override options in the second.
972  * Options set to "" will not be output.
973  */
974 function wfArrayToCGI( $array1, $array2 = NULL )
975 {
976         if ( !is_null( $array2 ) ) {
977                 $array1 = $array1 + $array2;
978         }
979
980         $cgi = '';
981         foreach ( $array1 as $key => $value ) {
982                 if ( '' !== $value ) {
983                         if ( '' != $cgi ) {
984                                 $cgi .= '&';
985                         }
986                         $cgi .= urlencode( $key ) . '=' . urlencode( $value );
987                 }
988         }
989         return $cgi;
990 }
991
992 /**
993  * Append a query string to an existing URL, which may or may not already
994  * have query string parameters already. If so, they will be combined.
995  *
996  * @param string $url
997  * @param string $query
998  * @return string
999  */
1000 function wfAppendQuery( $url, $query ) {
1001         if( $query != '' ) {
1002                 if( false === strpos( $url, '?' ) ) {
1003                         $url .= '?';
1004                 } else {
1005                         $url .= '&';
1006                 }
1007                 $url .= $query;
1008         }
1009         return $url;
1010 }
1011
1012 /**
1013  * This is obsolete, use SquidUpdate::purge()
1014  * @deprecated
1015  */
1016 function wfPurgeSquidServers ($urlArr) {
1017         SquidUpdate::purge( $urlArr );
1018 }
1019
1020 /**
1021  * Windows-compatible version of escapeshellarg()
1022  * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1023  * function puts single quotes in regardless of OS
1024  */
1025 function wfEscapeShellArg( ) {
1026         $args = func_get_args();
1027         $first = true;
1028         $retVal = '';
1029         foreach ( $args as $arg ) {
1030                 if ( !$first ) {
1031                         $retVal .= ' ';
1032                 } else {
1033                         $first = false;
1034                 }
1035
1036                 if ( wfIsWindows() ) {
1037                         // Escaping for an MSVC-style command line parser
1038                         // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1039                         // Double the backslashes before any double quotes. Escape the double quotes.
1040                         $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1041                         $arg = '';
1042                         $delim = false;
1043                         foreach ( $tokens as $token ) {
1044                                 if ( $delim ) {
1045                                         $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1046                                 } else {
1047                                         $arg .= $token;
1048                                 }
1049                                 $delim = !$delim;
1050                         }
1051                         // Double the backslashes before the end of the string, because
1052                         // we will soon add a quote
1053                         $m = array();
1054                         if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1055                                 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1056                         }
1057
1058                         // Add surrounding quotes
1059                         $retVal .= '"' . $arg . '"';
1060                 } else {
1061                         $retVal .= escapeshellarg( $arg );
1062                 }
1063         }
1064         return $retVal;
1065 }
1066
1067 /**
1068  * wfMerge attempts to merge differences between three texts.
1069  * Returns true for a clean merge and false for failure or a conflict.
1070  */
1071 function wfMerge( $old, $mine, $yours, &$result ){
1072         global $wgDiff3;
1073
1074         # This check may also protect against code injection in
1075         # case of broken installations.
1076         if(! file_exists( $wgDiff3 ) ){
1077                 wfDebug( "diff3 not found\n" );
1078                 return false;
1079         }
1080
1081         # Make temporary files
1082         $td = wfTempDir();
1083         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1084         $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1085         $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1086
1087         fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1088         fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1089         fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1090
1091         # Check for a conflict
1092         $cmd = $wgDiff3 . ' -a --overlap-only ' .
1093           wfEscapeShellArg( $mytextName ) . ' ' .
1094           wfEscapeShellArg( $oldtextName ) . ' ' .
1095           wfEscapeShellArg( $yourtextName );
1096         $handle = popen( $cmd, 'r' );
1097
1098         if( fgets( $handle, 1024 ) ){
1099                 $conflict = true;
1100         } else {
1101                 $conflict = false;
1102         }
1103         pclose( $handle );
1104
1105         # Merge differences
1106         $cmd = $wgDiff3 . ' -a -e --merge ' .
1107           wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1108         $handle = popen( $cmd, 'r' );
1109         $result = '';
1110         do {
1111                 $data = fread( $handle, 8192 );
1112                 if ( strlen( $data ) == 0 ) {
1113                         break;
1114                 }
1115                 $result .= $data;
1116         } while ( true );
1117         pclose( $handle );
1118         unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1119
1120         if ( $result === '' && $old !== '' && $conflict == false ) {
1121                 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1122                 $conflict = true;
1123         }
1124         return ! $conflict;
1125 }
1126
1127 /**
1128  * @todo document
1129  */
1130 function wfVarDump( $var ) {
1131         global $wgOut;
1132         $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1133         if ( headers_sent() || !@is_object( $wgOut ) ) {
1134                 print $s;
1135         } else {
1136                 $wgOut->addHTML( $s );
1137         }
1138 }
1139
1140 /**
1141  * Provide a simple HTTP error.
1142  */
1143 function wfHttpError( $code, $label, $desc ) {
1144         global $wgOut;
1145         $wgOut->disable();
1146         header( "HTTP/1.0 $code $label" );
1147         header( "Status: $code $label" );
1148         $wgOut->sendCacheControl();
1149
1150         header( 'Content-type: text/html; charset=utf-8' );
1151         print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1152                 "<html><head><title>" .
1153                 htmlspecialchars( $label ) .
1154                 "</title></head><body><h1>" .
1155                 htmlspecialchars( $label ) .
1156                 "</h1><p>" .
1157                 nl2br( htmlspecialchars( $desc ) ) .
1158                 "</p></body></html>\n";
1159 }
1160
1161 /**
1162  * Clear away any user-level output buffers, discarding contents.
1163  *
1164  * Suitable for 'starting afresh', for instance when streaming
1165  * relatively large amounts of data without buffering, or wanting to
1166  * output image files without ob_gzhandler's compression.
1167  *
1168  * The optional $resetGzipEncoding parameter controls suppression of
1169  * the Content-Encoding header sent by ob_gzhandler; by default it
1170  * is left. See comments for wfClearOutputBuffers() for why it would
1171  * be used.
1172  *
1173  * Note that some PHP configuration options may add output buffer
1174  * layers which cannot be removed; these are left in place.
1175  *
1176  * @param bool $resetGzipEncoding
1177  */
1178 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1179         if( $resetGzipEncoding ) {
1180                 // Suppress Content-Encoding and Content-Length
1181                 // headers from 1.10+s wfOutputHandler
1182                 global $wgDisableOutputCompression;
1183                 $wgDisableOutputCompression = true;
1184         }
1185         while( $status = ob_get_status() ) {
1186                 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1187                         // Probably from zlib.output_compression or other
1188                         // PHP-internal setting which can't be removed.
1189                         //
1190                         // Give up, and hope the result doesn't break
1191                         // output behavior.
1192                         break;
1193                 }
1194                 if( !ob_end_clean() ) {
1195                         // Could not remove output buffer handler; abort now
1196                         // to avoid getting in some kind of infinite loop.
1197                         break;
1198                 }
1199                 if( $resetGzipEncoding ) {
1200                         if( $status['name'] == 'ob_gzhandler' ) {
1201                                 // Reset the 'Content-Encoding' field set by this handler
1202                                 // so we can start fresh.
1203                                 header( 'Content-Encoding:' );
1204                         }
1205                 }
1206         }
1207 }
1208
1209 /**
1210  * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1211  *
1212  * Clear away output buffers, but keep the Content-Encoding header
1213  * produced by ob_gzhandler, if any.
1214  *
1215  * This should be used for HTTP 304 responses, where you need to
1216  * preserve the Content-Encoding header of the real result, but
1217  * also need to suppress the output of ob_gzhandler to keep to spec
1218  * and avoid breaking Firefox in rare cases where the headers and
1219  * body are broken over two packets.
1220  */
1221 function wfClearOutputBuffers() {
1222         wfResetOutputBuffers( false );
1223 }
1224
1225 /**
1226  * Converts an Accept-* header into an array mapping string values to quality
1227  * factors
1228  */
1229 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1230         # No arg means accept anything (per HTTP spec)
1231         if( !$accept ) {
1232                 return array( $def => 1 );
1233         }
1234
1235         $prefs = array();
1236
1237         $parts = explode( ',', $accept );
1238
1239         foreach( $parts as $part ) {
1240                 # FIXME: doesn't deal with params like 'text/html; level=1'
1241                 @list( $value, $qpart ) = explode( ';', $part );
1242                 $match = array();
1243                 if( !isset( $qpart ) ) {
1244                         $prefs[$value] = 1;
1245                 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1246                         $prefs[$value] = $match[1];
1247                 }
1248         }
1249
1250         return $prefs;
1251 }
1252
1253 /**
1254  * Checks if a given MIME type matches any of the keys in the given
1255  * array. Basic wildcards are accepted in the array keys.
1256  *
1257  * Returns the matching MIME type (or wildcard) if a match, otherwise
1258  * NULL if no match.
1259  *
1260  * @param string $type
1261  * @param array $avail
1262  * @return string
1263  * @private
1264  */
1265 function mimeTypeMatch( $type, $avail ) {
1266         if( array_key_exists($type, $avail) ) {
1267                 return $type;
1268         } else {
1269                 $parts = explode( '/', $type );
1270                 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1271                         return $parts[0] . '/*';
1272                 } elseif( array_key_exists( '*/*', $avail ) ) {
1273                         return '*/*';
1274                 } else {
1275                         return NULL;
1276                 }
1277         }
1278 }
1279
1280 /**
1281  * Returns the 'best' match between a client's requested internet media types
1282  * and the server's list of available types. Each list should be an associative
1283  * array of type to preference (preference is a float between 0.0 and 1.0).
1284  * Wildcards in the types are acceptable.
1285  *
1286  * @param array $cprefs Client's acceptable type list
1287  * @param array $sprefs Server's offered types
1288  * @return string
1289  *
1290  * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1291  * XXX: generalize to negotiate other stuff
1292  */
1293 function wfNegotiateType( $cprefs, $sprefs ) {
1294         $combine = array();
1295
1296         foreach( array_keys($sprefs) as $type ) {
1297                 $parts = explode( '/', $type );
1298                 if( $parts[1] != '*' ) {
1299                         $ckey = mimeTypeMatch( $type, $cprefs );
1300                         if( $ckey ) {
1301                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1302                         }
1303                 }
1304         }
1305
1306         foreach( array_keys( $cprefs ) as $type ) {
1307                 $parts = explode( '/', $type );
1308                 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1309                         $skey = mimeTypeMatch( $type, $sprefs );
1310                         if( $skey ) {
1311                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1312                         }
1313                 }
1314         }
1315
1316         $bestq = 0;
1317         $besttype = NULL;
1318
1319         foreach( array_keys( $combine ) as $type ) {
1320                 if( $combine[$type] > $bestq ) {
1321                         $besttype = $type;
1322                         $bestq = $combine[$type];
1323                 }
1324         }
1325
1326         return $besttype;
1327 }
1328
1329 /**
1330  * Array lookup
1331  * Returns an array where the values in the first array are replaced by the
1332  * values in the second array with the corresponding keys
1333  *
1334  * @return array
1335  */
1336 function wfArrayLookup( $a, $b ) {
1337         return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1338 }
1339
1340 /**
1341  * Convenience function; returns MediaWiki timestamp for the present time.
1342  * @return string
1343  */
1344 function wfTimestampNow() {
1345         # return NOW
1346         return wfTimestamp( TS_MW, time() );
1347 }
1348
1349 /**
1350  * Reference-counted warning suppression
1351  */
1352 function wfSuppressWarnings( $end = false ) {
1353         static $suppressCount = 0;
1354         static $originalLevel = false;
1355
1356         if ( $end ) {
1357                 if ( $suppressCount ) {
1358                         --$suppressCount;
1359                         if ( !$suppressCount ) {
1360                                 error_reporting( $originalLevel );
1361                         }
1362                 }
1363         } else {
1364                 if ( !$suppressCount ) {
1365                         $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1366                 }
1367                 ++$suppressCount;
1368         }
1369 }
1370
1371 /**
1372  * Restore error level to previous value
1373  */
1374 function wfRestoreWarnings() {
1375         wfSuppressWarnings( true );
1376 }
1377
1378 # Autodetect, convert and provide timestamps of various types
1379
1380 /**
1381  * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1382  */
1383 define('TS_UNIX', 0);
1384
1385 /**
1386  * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1387  */
1388 define('TS_MW', 1);
1389
1390 /**
1391  * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1392  */
1393 define('TS_DB', 2);
1394
1395 /**
1396  * RFC 2822 format, for E-mail and HTTP headers
1397  */
1398 define('TS_RFC2822', 3);
1399
1400 /**
1401  * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1402  *
1403  * This is used by Special:Export
1404  */
1405 define('TS_ISO_8601', 4);
1406
1407 /**
1408  * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1409  *
1410  * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1411  *       DateTime tag and page 36 for the DateTimeOriginal and
1412  *       DateTimeDigitized tags.
1413  */
1414 define('TS_EXIF', 5);
1415
1416 /**
1417  * Oracle format time.
1418  */
1419 define('TS_ORACLE', 6);
1420
1421 /**
1422  * Postgres format time.
1423  */
1424 define('TS_POSTGRES', 7);
1425
1426 /**
1427  * @param mixed $outputtype A timestamp in one of the supported formats, the
1428  *                          function will autodetect which format is supplied
1429  *                          and act accordingly.
1430  * @return string Time in the format specified in $outputtype
1431  */
1432 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1433         $uts = 0;
1434         $da = array();
1435         if ($ts==0) {
1436                 $uts=time();
1437         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1438                 # TS_DB
1439                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1440                             (int)$da[2],(int)$da[3],(int)$da[1]);
1441         } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1442                 # TS_EXIF
1443                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1444                         (int)$da[2],(int)$da[3],(int)$da[1]);
1445         } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1446                 # TS_MW
1447                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1448                             (int)$da[2],(int)$da[3],(int)$da[1]);
1449         } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1450                 # TS_UNIX
1451                 $uts = $ts;
1452         } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1453                 # TS_ORACLE
1454                 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1455                                 str_replace("+00:00", "UTC", $ts)));
1456         } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1457                 # TS_ISO_8601
1458                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1459                         (int)$da[2],(int)$da[3],(int)$da[1]);
1460         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1461                 # TS_POSTGRES
1462                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1463                 (int)$da[2],(int)$da[3],(int)$da[1]);
1464         } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1465                 # TS_POSTGRES
1466                 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1467                 (int)$da[2],(int)$da[3],(int)$da[1]);
1468         } else {
1469                 # Bogus value; fall back to the epoch...
1470                 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1471                 $uts = 0;
1472         }
1473
1474
1475         switch($outputtype) {
1476                 case TS_UNIX:
1477                         return $uts;
1478                 case TS_MW:
1479                         return gmdate( 'YmdHis', $uts );
1480                 case TS_DB:
1481                         return gmdate( 'Y-m-d H:i:s', $uts );
1482                 case TS_ISO_8601:
1483                         return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1484                 // This shouldn't ever be used, but is included for completeness
1485                 case TS_EXIF:
1486                         return gmdate(  'Y:m:d H:i:s', $uts );
1487                 case TS_RFC2822:
1488                         return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1489                 case TS_ORACLE:
1490                         return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1491                 case TS_POSTGRES:
1492                         return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1493                 default:
1494                         throw new MWException( 'wfTimestamp() called with illegal output type.');
1495         }
1496 }
1497
1498 /**
1499  * Return a formatted timestamp, or null if input is null.
1500  * For dealing with nullable timestamp columns in the database.
1501  * @param int $outputtype
1502  * @param string $ts
1503  * @return string
1504  */
1505 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1506         if( is_null( $ts ) ) {
1507                 return null;
1508         } else {
1509                 return wfTimestamp( $outputtype, $ts );
1510         }
1511 }
1512
1513 /**
1514  * Check if the operating system is Windows
1515  *
1516  * @return bool True if it's Windows, False otherwise.
1517  */
1518 function wfIsWindows() {
1519         if (substr(php_uname(), 0, 7) == 'Windows') {
1520                 return true;
1521         } else {
1522                 return false;
1523         }
1524 }
1525
1526 /**
1527  * Swap two variables
1528  */
1529 function swap( &$x, &$y ) {
1530         $z = $x;
1531         $x = $y;
1532         $y = $z;
1533 }
1534
1535 function wfGetCachedNotice( $name ) {
1536         global $wgOut, $parserMemc;
1537         $fname = 'wfGetCachedNotice';
1538         wfProfileIn( $fname );
1539         
1540         $needParse = false;
1541         
1542         if( $name === 'default' ) {
1543                 // special case
1544                 global $wgSiteNotice;
1545                 $notice = $wgSiteNotice;
1546                 if( empty( $notice ) ) {
1547                         wfProfileOut( $fname );
1548                         return false;
1549                 }
1550         } else {
1551                 $notice = wfMsgForContentNoTrans( $name );
1552                 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1553                         wfProfileOut( $fname );
1554                         return( false );
1555                 }
1556         }
1557         
1558         $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1559         if( is_array( $cachedNotice ) ) {
1560                 if( md5( $notice ) == $cachedNotice['hash'] ) {
1561                         $notice = $cachedNotice['html'];
1562                 } else {
1563                         $needParse = true;
1564                 }
1565         } else {
1566                 $needParse = true;
1567         }
1568         
1569         if( $needParse ) {
1570                 if( is_object( $wgOut ) ) {
1571                         $parsed = $wgOut->parse( $notice );
1572                         $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1573                         $notice = $parsed;
1574                 } else {
1575                         wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1576                         $notice = '';
1577                 }
1578         }
1579         
1580         wfProfileOut( $fname );
1581         return $notice;
1582 }
1583
1584 function wfGetNamespaceNotice() {
1585         global $wgTitle;
1586         
1587         # Paranoia
1588         if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1589                 return "";
1590
1591         $fname = 'wfGetNamespaceNotice';
1592         wfProfileIn( $fname );
1593         
1594         $key = "namespacenotice-" . $wgTitle->getNsText();
1595         $namespaceNotice = wfGetCachedNotice( $key );
1596         if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1597                  $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1598         } else {
1599                 $namespaceNotice = "";
1600         }
1601
1602         wfProfileOut( $fname );
1603         return $namespaceNotice;
1604 }
1605
1606 function wfGetSiteNotice() {
1607         global $wgUser, $wgSiteNotice;
1608         $fname = 'wfGetSiteNotice';
1609         wfProfileIn( $fname );
1610         $siteNotice = '';       
1611         
1612         if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1613                 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1614                         $siteNotice = wfGetCachedNotice( 'sitenotice' );
1615                 } else {
1616                         $anonNotice = wfGetCachedNotice( 'anonnotice' );
1617                         if( !$anonNotice ) {
1618                                 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1619                         } else {
1620                                 $siteNotice = $anonNotice;
1621                         }
1622                 }
1623                 if( !$siteNotice ) {
1624                         $siteNotice = wfGetCachedNotice( 'default' );
1625                 }
1626         }
1627
1628         wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1629         wfProfileOut( $fname );
1630         return $siteNotice;
1631 }
1632
1633 /** 
1634  * BC wrapper for MimeMagic::singleton()
1635  * @deprecated
1636  */
1637 function &wfGetMimeMagic() {
1638         return MimeMagic::singleton();
1639 }
1640
1641 /**
1642  * Tries to get the system directory for temporary files.
1643  * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1644  * and if none are set /tmp is returned as the generic Unix default.
1645  *
1646  * NOTE: When possible, use the tempfile() function to create temporary
1647  * files to avoid race conditions on file creation, etc.
1648  *
1649  * @return string
1650  */
1651 function wfTempDir() {
1652         foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1653                 $tmp = getenv( $var );
1654                 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1655                         return $tmp;
1656                 }
1657         }
1658         # Hope this is Unix of some kind!
1659         return '/tmp';
1660 }
1661
1662 /**
1663  * Make directory, and make all parent directories if they don't exist
1664  */
1665 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1666         if( strval( $fullDir ) === '' )
1667                 return true;
1668         if( file_exists( $fullDir ) )
1669                 return true;
1670         return mkdir( str_replace( '/', DIRECTORY_SEPARATOR, $fullDir ), $mode, true );
1671 }
1672
1673 /**
1674  * Increment a statistics counter
1675  */
1676  function wfIncrStats( $key ) {
1677          global $wgMemc;
1678          $key = wfMemcKey( 'stats', $key );
1679          if ( is_null( $wgMemc->incr( $key ) ) ) {
1680                  $wgMemc->add( $key, 1 );
1681          }
1682  }
1683
1684 /**
1685  * @param mixed $nr The number to format
1686  * @param int $acc The number of digits after the decimal point, default 2
1687  * @param bool $round Whether or not to round the value, default true
1688  * @return float
1689  */
1690 function wfPercent( $nr, $acc = 2, $round = true ) {
1691         $ret = sprintf( "%.${acc}f", $nr );
1692         return $round ? round( $ret, $acc ) . '%' : "$ret%";
1693 }
1694
1695 /**
1696  * Encrypt a username/password.
1697  *
1698  * @param string $userid ID of the user
1699  * @param string $password Password of the user
1700  * @return string Hashed password
1701  */
1702 function wfEncryptPassword( $userid, $password ) {
1703         global $wgPasswordSalt;
1704         $p = md5( $password);
1705
1706         if($wgPasswordSalt)
1707                 return md5( "{$userid}-{$p}" );
1708         else
1709                 return $p;
1710 }
1711
1712 /**
1713  * Appends to second array if $value differs from that in $default
1714  */
1715 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1716         if ( is_null( $changed ) ) {
1717                 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1718         }
1719         if ( $default[$key] !== $value ) {
1720                 $changed[$key] = $value;
1721         }
1722 }
1723
1724 /**
1725  * Since wfMsg() and co suck, they don't return false if the message key they
1726  * looked up didn't exist but a XHTML string, this function checks for the
1727  * nonexistance of messages by looking at wfMsg() output
1728  *
1729  * @param $msg      The message key looked up
1730  * @param $wfMsgOut The output of wfMsg*()
1731  * @return bool
1732  */
1733 function wfEmptyMsg( $msg, $wfMsgOut ) {
1734         return $wfMsgOut === htmlspecialchars( "<$msg>" );
1735 }
1736
1737 /**
1738  * Find out whether or not a mixed variable exists in a string
1739  *
1740  * @param mixed  needle
1741  * @param string haystack
1742  * @return bool
1743  */
1744 function in_string( $needle, $str ) {
1745         return strpos( $str, $needle ) !== false;
1746 }
1747
1748 function wfSpecialList( $page, $details ) {
1749         global $wgContLang;
1750         $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1751         return $page . $details;
1752 }
1753
1754 /**
1755  * Returns a regular expression of url protocols
1756  *
1757  * @return string
1758  */
1759 function wfUrlProtocols() {
1760         global $wgUrlProtocols;
1761
1762         // Support old-style $wgUrlProtocols strings, for backwards compatibility
1763         // with LocalSettings files from 1.5
1764         if ( is_array( $wgUrlProtocols ) ) {
1765                 $protocols = array();
1766                 foreach ($wgUrlProtocols as $protocol)
1767                         $protocols[] = preg_quote( $protocol, '/' );
1768
1769                 return implode( '|', $protocols );
1770         } else {
1771                 return $wgUrlProtocols;
1772         }
1773 }
1774
1775 /**
1776  * Execute a shell command, with time and memory limits mirrored from the PHP
1777  * configuration if supported.
1778  * @param $cmd Command line, properly escaped for shell.
1779  * @param &$retval optional, will receive the program's exit code.
1780  *                 (non-zero is usually failure)
1781  * @return collected stdout as a string (trailing newlines stripped)
1782  */
1783 function wfShellExec( $cmd, &$retval=null ) {
1784         global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1785         
1786         if( ini_get( 'safe_mode' ) ) {
1787                 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1788                 $retval = 1;
1789                 return "Unable to run external programs in safe mode.";
1790         }
1791
1792         if ( php_uname( 's' ) == 'Linux' ) {
1793                 $time = intval( ini_get( 'max_execution_time' ) );
1794                 $mem = intval( $wgMaxShellMemory );
1795                 $filesize = intval( $wgMaxShellFileSize );
1796
1797                 if ( $time > 0 && $mem > 0 ) {
1798                         $script = "$IP/bin/ulimit4.sh";
1799                         if ( is_executable( $script ) ) {
1800                                 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1801                         }
1802                 }
1803         } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1804                 # This is a hack to work around PHP's flawed invocation of cmd.exe
1805                 # http://news.php.net/php.internals/21796
1806                 $cmd = '"' . $cmd . '"';
1807         }
1808         wfDebug( "wfShellExec: $cmd\n" );
1809         
1810         $output = array();
1811         $retval = 1; // error by default?
1812         exec( $cmd, $output, $retval ); // returns the last line of output.
1813         return implode( "\n", $output );
1814         
1815 }
1816
1817 /**
1818  * This function works like "use VERSION" in Perl, the program will die with a
1819  * backtrace if the current version of PHP is less than the version provided
1820  *
1821  * This is useful for extensions which due to their nature are not kept in sync
1822  * with releases, and might depend on other versions of PHP than the main code
1823  *
1824  * Note: PHP might die due to parsing errors in some cases before it ever
1825  *       manages to call this function, such is life
1826  *
1827  * @see perldoc -f use
1828  *
1829  * @param mixed $version The version to check, can be a string, an integer, or
1830  *                       a float
1831  */
1832 function wfUsePHP( $req_ver ) {
1833         $php_ver = PHP_VERSION;
1834
1835         if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1836                  throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1837 }
1838
1839 /**
1840  * This function works like "use VERSION" in Perl except it checks the version
1841  * of MediaWiki, the program will die with a backtrace if the current version
1842  * of MediaWiki is less than the version provided.
1843  *
1844  * This is useful for extensions which due to their nature are not kept in sync
1845  * with releases
1846  *
1847  * @see perldoc -f use
1848  *
1849  * @param mixed $version The version to check, can be a string, an integer, or
1850  *                       a float
1851  */
1852 function wfUseMW( $req_ver ) {
1853         global $wgVersion;
1854
1855         if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1856                 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1857 }
1858
1859 /**
1860  * @deprecated use StringUtils::escapeRegexReplacement
1861  */
1862 function wfRegexReplacement( $string ) {
1863         return StringUtils::escapeRegexReplacement( $string );
1864 }
1865
1866 /**
1867  * Return the final portion of a pathname.
1868  * Reimplemented because PHP5's basename() is buggy with multibyte text.
1869  * http://bugs.php.net/bug.php?id=33898
1870  *
1871  * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1872  * We'll consider it so always, as we don't want \s in our Unix paths either.
1873  * 
1874  * @param string $path
1875  * @param string $suffix to remove if present
1876  * @return string
1877  */
1878 function wfBaseName( $path, $suffix='' ) {
1879         $encSuffix = ($suffix == '')
1880                 ? ''
1881                 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1882         $matches = array();
1883         if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1884                 return $matches[1];
1885         } else {
1886                 return '';
1887         }
1888 }
1889
1890 /**
1891  * Generate a relative path name to the given file.
1892  * May explode on non-matching case-insensitive paths,
1893  * funky symlinks, etc.
1894  *
1895  * @param string $path Absolute destination path including target filename
1896  * @param string $from Absolute source path, directory only
1897  * @return string
1898  */
1899 function wfRelativePath( $path, $from ) {
1900         // Normalize mixed input on Windows...
1901         $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1902         $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1903         
1904         $pieces  = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1905         $against = explode( DIRECTORY_SEPARATOR, $from );
1906
1907         // Trim off common prefix
1908         while( count( $pieces ) && count( $against )
1909                 && $pieces[0] == $against[0] ) {
1910                 array_shift( $pieces );
1911                 array_shift( $against );
1912         }
1913
1914         // relative dots to bump us to the parent
1915         while( count( $against ) ) {
1916                 array_unshift( $pieces, '..' );
1917                 array_shift( $against );
1918         }
1919
1920         array_push( $pieces, wfBaseName( $path ) );
1921
1922         return implode( DIRECTORY_SEPARATOR, $pieces );
1923 }
1924
1925 /**
1926  * Make a URL index, appropriate for the el_index field of externallinks.
1927  */
1928 function wfMakeUrlIndex( $url ) {
1929         global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1930         $bits = parse_url( $url );
1931         wfSuppressWarnings();
1932         wfRestoreWarnings();
1933         if ( !$bits ) {
1934                 return false;
1935         }
1936         // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1937         $delimiter = '';
1938         if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1939                 $delimiter = '://';
1940         } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1941                 $delimiter = ':';
1942                 // parse_url detects for news: and mailto: the host part of an url as path
1943                 // We have to correct this wrong detection
1944                 if ( isset ( $bits['path'] ) ) { 
1945                         $bits['host'] = $bits['path'];
1946                         $bits['path'] = '';
1947                 }
1948         } else {
1949                 return false;
1950         }
1951
1952         // Reverse the labels in the hostname, convert to lower case
1953         // For emails reverse domainpart only
1954         if ( $bits['scheme'] == 'mailto' ) {
1955                 $mailparts = explode( '@', $bits['host'] );
1956                 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1957                 $reversedHost = $domainpart . '@' . $mailparts[0];
1958         } else {
1959                 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1960         }
1961         // Add an extra dot to the end
1962         if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1963                 $reversedHost .= '.';
1964         }
1965         // Reconstruct the pseudo-URL
1966         $prot = $bits['scheme'];
1967         $index = "$prot$delimiter$reversedHost";
1968         // Leave out user and password. Add the port, path, query and fragment
1969         if ( isset( $bits['port'] ) )      $index .= ':' . $bits['port'];
1970         if ( isset( $bits['path'] ) ) {
1971                 $index .= $bits['path'];
1972         } else {
1973                 $index .= '/';
1974         }
1975         if ( isset( $bits['query'] ) )     $index .= '?' . $bits['query'];
1976         if ( isset( $bits['fragment'] ) )  $index .= '#' . $bits['fragment'];
1977         return $index;
1978 }
1979
1980 /**
1981  * Do any deferred updates and clear the list
1982  * TODO: This could be in Wiki.php if that class made any sense at all
1983  */
1984 function wfDoUpdates()
1985 {
1986         global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1987         foreach ( $wgDeferredUpdateList as $update ) {
1988                 $update->doUpdate();
1989         }
1990         foreach ( $wgPostCommitUpdateList as $update ) {
1991                 $update->doUpdate();
1992         }
1993         $wgDeferredUpdateList = array();
1994         $wgPostCommitUpdateList = array();
1995 }
1996
1997 /**
1998  * @deprecated use StringUtils::explodeMarkup
1999  */
2000 function wfExplodeMarkup( $separator, $text ) {
2001         return StringUtils::explodeMarkup( $separator, $text );
2002 }
2003
2004 /**
2005  * Convert an arbitrarily-long digit string from one numeric base
2006  * to another, optionally zero-padding to a minimum column width.
2007  *
2008  * Supports base 2 through 36; digit values 10-36 are represented
2009  * as lowercase letters a-z. Input is case-insensitive.
2010  *
2011  * @param $input string of digits
2012  * @param $sourceBase int 2-36
2013  * @param $destBase int 2-36
2014  * @param $pad int 1 or greater
2015  * @param $lowercase bool
2016  * @return string or false on invalid input
2017  */
2018 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2019         $input = strval( $input );
2020         if( $sourceBase < 2 ||
2021                 $sourceBase > 36 ||
2022                 $destBase < 2 ||
2023                 $destBase > 36 ||
2024                 $pad < 1 ||
2025                 $sourceBase != intval( $sourceBase ) ||
2026                 $destBase != intval( $destBase ) ||
2027                 $pad != intval( $pad ) ||
2028                 !is_string( $input ) ||
2029                 $input == '' ) {
2030                 return false;
2031         }
2032         $digitChars = ( $lowercase ) ?  '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2033         $inDigits = array();
2034         $outChars = '';
2035         
2036         // Decode and validate input string
2037         $input = strtolower( $input );
2038         for( $i = 0; $i < strlen( $input ); $i++ ) {
2039                 $n = strpos( $digitChars, $input{$i} );
2040                 if( $n === false || $n > $sourceBase ) {
2041                         return false;
2042                 }
2043                 $inDigits[] = $n;
2044         }
2045         
2046         // Iterate over the input, modulo-ing out an output digit
2047         // at a time until input is gone.
2048         while( count( $inDigits ) ) {
2049                 $work = 0;
2050                 $workDigits = array();
2051                 
2052                 // Long division...
2053                 foreach( $inDigits as $digit ) {
2054                         $work *= $sourceBase;
2055                         $work += $digit;
2056                         
2057                         if( $work < $destBase ) {
2058                                 // Gonna need to pull another digit.
2059                                 if( count( $workDigits ) ) {
2060                                         // Avoid zero-padding; this lets us find
2061                                         // the end of the input very easily when
2062                                         // length drops to zero.
2063                                         $workDigits[] = 0;
2064                                 }
2065                         } else {
2066                                 // Finally! Actual division!
2067                                 $workDigits[] = intval( $work / $destBase );
2068                                 
2069                                 // Isn't it annoying that most programming languages
2070                                 // don't have a single divide-and-remainder operator,
2071                                 // even though the CPU implements it that way?
2072                                 $work = $work % $destBase;
2073                         }
2074                 }
2075                 
2076                 // All that division leaves us with a remainder,
2077                 // which is conveniently our next output digit.
2078                 $outChars .= $digitChars[$work];
2079                 
2080                 // And we continue!
2081                 $inDigits = $workDigits;
2082         }
2083         
2084         while( strlen( $outChars ) < $pad ) {
2085                 $outChars .= '0';
2086         }
2087         
2088         return strrev( $outChars );
2089 }
2090
2091 /**
2092  * Create an object with a given name and an array of construct parameters
2093  * @param string $name
2094  * @param array $p parameters
2095  */
2096 function wfCreateObject( $name, $p ){
2097         $p = array_values( $p );
2098         switch ( count( $p ) ) {
2099                 case 0:
2100                         return new $name;
2101                 case 1:
2102                         return new $name( $p[0] );
2103                 case 2:
2104                         return new $name( $p[0], $p[1] );
2105                 case 3:
2106                         return new $name( $p[0], $p[1], $p[2] );
2107                 case 4:
2108                         return new $name( $p[0], $p[1], $p[2], $p[3] );
2109                 case 5:
2110                         return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2111                 case 6:
2112                         return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2113                 default:
2114                         throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2115         }
2116 }
2117
2118 /**
2119  * Aliases for modularized functions
2120  */
2121 function wfGetHTTP( $url, $timeout = 'default' ) { 
2122         return Http::get( $url, $timeout ); 
2123 }
2124 function wfIsLocalURL( $url ) { 
2125         return Http::isLocalURL( $url ); 
2126 }
2127
2128 /**
2129  * Initialise php session
2130  */
2131 function wfSetupSession() {
2132         global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2133         if( $wgSessionsInMemcached ) {
2134                 require_once( 'MemcachedSessions.php' );
2135         } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2136                 # If it's left on 'user' or another setting from another
2137                 # application, it will end up failing. Try to recover.
2138                 ini_set ( 'session.save_handler', 'files' );
2139         }
2140         session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2141         session_cache_limiter( 'private, must-revalidate' );
2142         @session_start();
2143 }
2144
2145 /**
2146  * Get an object from the precompiled serialized directory
2147  *
2148  * @return mixed The variable on success, false on failure
2149  */
2150 function wfGetPrecompiledData( $name ) {
2151         global $IP;
2152
2153         $file = "$IP/serialized/$name";
2154         if ( file_exists( $file ) ) {
2155                 $blob = file_get_contents( $file );
2156                 if ( $blob ) {
2157                         return unserialize( $blob );
2158                 }
2159         }
2160         return false;
2161 }
2162
2163 function wfGetCaller( $level = 2 ) {
2164         $backtrace = wfDebugBacktrace();
2165         if ( isset( $backtrace[$level] ) ) {
2166                 if ( isset( $backtrace[$level]['class'] ) ) {
2167                         $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2168                 } else {
2169                         $caller = $backtrace[$level]['function'];
2170                 }
2171         } else {
2172                 $caller = 'unknown';
2173         }
2174         return $caller;
2175 }
2176
2177 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2178 function wfGetAllCallers() {
2179         return implode('/', array_map(
2180                 create_function('$frame',' 
2181                         return isset( $frame["class"] )?
2182                                 $frame["class"]."::".$frame["function"]:
2183                                 $frame["function"]; 
2184                         '),
2185                 array_reverse(wfDebugBacktrace())));
2186 }
2187
2188 /**
2189  * Get a cache key
2190  */
2191 function wfMemcKey( /*... */ ) {
2192         global $wgDBprefix, $wgDBname;
2193         $args = func_get_args();
2194         if ( $wgDBprefix ) {
2195                 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2196         } else {
2197                 $key = $wgDBname . ':' . implode( ':', $args );
2198         }
2199         return $key;
2200 }
2201
2202 /**
2203  * Get a cache key for a foreign DB
2204  */
2205 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2206         $args = array_slice( func_get_args(), 2 );
2207         if ( $prefix ) {
2208                 $key = "$db-$prefix:" . implode( ':', $args );
2209         } else {
2210                 $key = $db . ':' . implode( ':', $args );
2211         }
2212         return $key;
2213 }
2214
2215 /**
2216  * Get an ASCII string identifying this wiki
2217  * This is used as a prefix in memcached keys
2218  */
2219 function wfWikiID() {
2220         global $wgDBprefix, $wgDBname;
2221         if ( $wgDBprefix ) {
2222                 return "$wgDBname-$wgDBprefix";
2223         } else {
2224                 return $wgDBname;
2225         }
2226 }
2227
2228 /*
2229  * Get a Database object
2230  * @param integer $db Index of the connection to get. May be DB_MASTER for the 
2231  *                master (for write queries), DB_SLAVE for potentially lagged 
2232  *                read queries, or an integer >= 0 for a particular server.
2233  *
2234  * @param mixed $groups Query groups. An array of group names that this query 
2235  *              belongs to. May contain a single string if the query is only 
2236  *              in one group.
2237  */
2238 function &wfGetDB( $db = DB_LAST, $groups = array() ) {
2239         global $wgLoadBalancer;
2240         $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2241         return $ret;
2242 }
2243
2244 /**
2245  * Find a file. 
2246  * Shortcut for RepoGroup::singleton()->findFile()
2247  * @param mixed $title Title object or string. May be interwiki.
2248  * @param mixed $time Requested time for an archived image, or false for the 
2249  *                    current version. An image object will be returned which 
2250  *                    existed at or before the specified time.
2251  * @return File, or false if the file does not exist
2252  */
2253 function wfFindFile( $title, $time = false ) {
2254         return RepoGroup::singleton()->findFile( $title, $time );
2255 }
2256
2257 /**
2258  * Get an object referring to a locally registered file.
2259  * Returns a valid placeholder object if the file does not exist.
2260  */
2261 function wfLocalFile( $title ) {
2262         return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2263 }
2264
2265 /**
2266  * Should low-performance queries be disabled?
2267  *
2268  * @return bool
2269  */
2270 function wfQueriesMustScale() {
2271         global $wgMiserMode;
2272         return $wgMiserMode
2273                 || ( SiteStats::pages() > 100000
2274                 && SiteStats::edits() > 1000000
2275                 && SiteStats::users() > 10000 );
2276 }
2277
2278 /**
2279  * Get the path to a specified script file, respecting file
2280  * extensions; this is a wrapper around $wgScriptExtension etc.
2281  *
2282  * @param string $script Script filename, sans extension
2283  * @return string
2284  */
2285 function wfScript( $script = 'index' ) {
2286         global $wgScriptPath, $wgScriptExtension;
2287         return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2288 }
2289
2290 /**
2291  * Convenience function converts boolean values into "true"
2292  * or "false" (string) values
2293  *
2294  * @param bool $value
2295  * @return string
2296  */
2297 function wfBoolToStr( $value ) {
2298         return $value ? 'true' : 'false';
2299 }
2300
2301 /**
2302  * Load an extension messages file
2303  */
2304 function wfLoadExtensionMessages( $extensionName ) {
2305         global $wgExtensionMessagesFiles, $wgMessageCache;
2306         if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2307                 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2308                 // Prevent double-loading
2309                 $wgExtensionMessagesFiles[$extensionName] = false;
2310         }
2311 }
2312
2313 /**
2314  * Get a platform-independent path to the null file, e.g.
2315  * /dev/null
2316  *
2317  * @return string
2318  */
2319 function wfGetNull() {
2320         return wfIsWindows()
2321                 ? 'NUL'
2322                 : '/dev/null';
2323 }