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