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