Use Doxygen @addtogroup instead of phpdoc @package && @subpackage
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 /**
4 * Global functions used everywhere
5 */
6
7 /**
8 * Some globals and requires needed
9 */
10
11 /** Total number of articles */
12 $wgNumberOfArticles = -1; # Unset
13
14 /** Total number of views */
15 $wgTotalViews = -1;
16
17 /** Total number of edits */
18 $wgTotalEdits = -1;
19
20
21 require_once( 'LogPage.php' );
22 require_once( 'normal/UtfNormalUtil.php' );
23 require_once( 'XmlFunctions.php' );
24
25 /**
26 * Compatibility functions
27 *
28 * We more or less support PHP 5.0.x and up.
29 * Re-implementations of newer functions or functions in non-standard
30 * PHP extensions may be included here.
31 */
32 if( !function_exists('iconv') ) {
33 # iconv support is not in the default configuration and so may not be present.
34 # Assume will only ever use utf-8 and iso-8859-1.
35 # This will *not* work in all circumstances.
36 function iconv( $from, $to, $string ) {
37 if(strcasecmp( $from, $to ) == 0) return $string;
38 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
39 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
40 return $string;
41 }
42 }
43
44 # UTF-8 substr function based on a PHP manual comment
45 if ( !function_exists( 'mb_substr' ) ) {
46 function mb_substr( $str, $start ) {
47 $ar = array();
48 preg_match_all( '/./us', $str, $ar );
49
50 if( func_num_args() >= 3 ) {
51 $end = func_get_arg( 2 );
52 return join( '', array_slice( $ar[0], $start, $end ) );
53 } else {
54 return join( '', array_slice( $ar[0], $start ) );
55 }
56 }
57 }
58
59 if ( !function_exists( 'array_diff_key' ) ) {
60 /**
61 * Exists in PHP 5.1.0+
62 * Not quite compatible, two-argument version only
63 * Null values will cause problems due to this use of isset()
64 */
65 function array_diff_key( $left, $right ) {
66 $result = $left;
67 foreach ( $left as $key => $unused ) {
68 if ( isset( $right[$key] ) ) {
69 unset( $result[$key] );
70 }
71 }
72 return $result;
73 }
74 }
75
76
77 /**
78 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
79 * PHP 5 won't let you declare a 'clone' function, even conditionally,
80 * so it has to be a wrapper with a different name.
81 */
82 function wfClone( $object ) {
83 return clone( $object );
84 }
85
86 /**
87 * Where as we got a random seed
88 */
89 $wgRandomSeeded = false;
90
91 /**
92 * Seed Mersenne Twister
93 * No-op for compatibility; only necessary in PHP < 4.2.0
94 */
95 function wfSeedRandom() {
96 /* No-op */
97 }
98
99 /**
100 * Get a random decimal value between 0 and 1, in a way
101 * not likely to give duplicate values for any realistic
102 * number of articles.
103 *
104 * @return string
105 */
106 function wfRandom() {
107 # The maximum random value is "only" 2^31-1, so get two random
108 # values to reduce the chance of dupes
109 $max = mt_getrandmax() + 1;
110 $rand = number_format( (mt_rand() * $max + mt_rand())
111 / $max / $max, 12, '.', '' );
112 return $rand;
113 }
114
115 /**
116 * We want / and : to be included as literal characters in our title URLs.
117 * %2F in the page titles seems to fatally break for some reason.
118 *
119 * @param $s String:
120 * @return string
121 */
122 function wfUrlencode ( $s ) {
123 $s = urlencode( $s );
124 $s = preg_replace( '/%3[Aa]/', ':', $s );
125 $s = preg_replace( '/%2[Ff]/', '/', $s );
126
127 return $s;
128 }
129
130 /**
131 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
132 * In normal operation this is a NOP.
133 *
134 * Controlling globals:
135 * $wgDebugLogFile - points to the log file
136 * $wgProfileOnly - if set, normal debug messages will not be recorded.
137 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
138 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
139 *
140 * @param $text String
141 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
142 */
143 function wfDebug( $text, $logonly = false ) {
144 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
145 static $recursion = 0;
146
147 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
148 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
149 return;
150 }
151
152 if ( $wgDebugComments && !$logonly ) {
153 if ( !isset( $wgOut ) ) {
154 return;
155 }
156 if ( !StubObject::isRealObject( $wgOut ) ) {
157 if ( $recursion ) {
158 return;
159 }
160 $recursion++;
161 $wgOut->_unstub();
162 $recursion--;
163 }
164 $wgOut->debug( $text );
165 }
166 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
167 # Strip unprintables; they can switch terminal modes when binary data
168 # gets dumped, which is pretty annoying.
169 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
170 @error_log( $text, 3, $wgDebugLogFile );
171 }
172 }
173
174 /**
175 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
176 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
177 *
178 * @param $logGroup String
179 * @param $text String
180 * @param $public Bool: whether to log the event in the public log if no private
181 * log file is specified, (default true)
182 */
183 function wfDebugLog( $logGroup, $text, $public = true ) {
184 global $wgDebugLogGroups;
185 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
186 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
187 $time = wfTimestamp( TS_DB );
188 $wiki = wfWikiID();
189 @error_log( "$time $wiki: $text", 3, $wgDebugLogGroups[$logGroup] );
190 } else if ( $public === true ) {
191 wfDebug( $text, true );
192 }
193 }
194
195 /**
196 * Log for database errors
197 * @param $text String: database error message.
198 */
199 function wfLogDBError( $text ) {
200 global $wgDBerrorLog;
201 if ( $wgDBerrorLog ) {
202 $host = trim(`hostname`);
203 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
204 error_log( $text, 3, $wgDBerrorLog );
205 }
206 }
207
208 /**
209 * @todo document
210 */
211 function wfLogProfilingData() {
212 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
213 global $wgProfiling, $wgUser;
214 if ( $wgProfiling ) {
215 $now = wfTime();
216 $elapsed = $now - $wgRequestTime;
217 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
218 $forward = '';
219 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
220 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
221 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
222 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
223 if( !empty( $_SERVER['HTTP_FROM'] ) )
224 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
225 if( $forward )
226 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
227 // Don't unstub $wgUser at this late stage just for statistics purposes
228 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
229 $forward .= ' anon';
230 $log = sprintf( "%s\t%04.3f\t%s\n",
231 gmdate( 'YmdHis' ), $elapsed,
232 urldecode( $wgRequest->getRequestURL() . $forward ) );
233 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
234 error_log( $log . $prof, 3, $wgDebugLogFile );
235 }
236 }
237 }
238
239 /**
240 * Check if the wiki read-only lock file is present. This can be used to lock
241 * off editing functions, but doesn't guarantee that the database will not be
242 * modified.
243 * @return bool
244 */
245 function wfReadOnly() {
246 global $wgReadOnlyFile, $wgReadOnly;
247
248 if ( !is_null( $wgReadOnly ) ) {
249 return (bool)$wgReadOnly;
250 }
251 if ( '' == $wgReadOnlyFile ) {
252 return false;
253 }
254 // Set $wgReadOnly for faster access next time
255 if ( is_file( $wgReadOnlyFile ) ) {
256 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
257 } else {
258 $wgReadOnly = false;
259 }
260 return (bool)$wgReadOnly;
261 }
262
263
264 /**
265 * Get a message from anywhere, for the current user language.
266 *
267 * Use wfMsgForContent() instead if the message should NOT
268 * change depending on the user preferences.
269 *
270 * Note that the message may contain HTML, and is therefore
271 * not safe for insertion anywhere. Some functions such as
272 * addWikiText will do the escaping for you. Use wfMsgHtml()
273 * if you need an escaped message.
274 *
275 * @param $key String: lookup key for the message, usually
276 * defined in languages/Language.php
277 *
278 * This function also takes extra optional parameters (not
279 * shown in the function definition), which can by used to
280 * insert variable text into the predefined message.
281 */
282 function wfMsg( $key ) {
283 $args = func_get_args();
284 array_shift( $args );
285 return wfMsgReal( $key, $args, true );
286 }
287
288 /**
289 * Same as above except doesn't transform the message
290 */
291 function wfMsgNoTrans( $key ) {
292 $args = func_get_args();
293 array_shift( $args );
294 return wfMsgReal( $key, $args, true, false, false );
295 }
296
297 /**
298 * Get a message from anywhere, for the current global language
299 * set with $wgLanguageCode.
300 *
301 * Use this if the message should NOT change dependent on the
302 * language set in the user's preferences. This is the case for
303 * most text written into logs, as well as link targets (such as
304 * the name of the copyright policy page). Link titles, on the
305 * other hand, should be shown in the UI language.
306 *
307 * Note that MediaWiki allows users to change the user interface
308 * language in their preferences, but a single installation
309 * typically only contains content in one language.
310 *
311 * Be wary of this distinction: If you use wfMsg() where you should
312 * use wfMsgForContent(), a user of the software may have to
313 * customize over 70 messages in order to, e.g., fix a link in every
314 * possible language.
315 *
316 * @param $key String: lookup key for the message, usually
317 * defined in languages/Language.php
318 */
319 function wfMsgForContent( $key ) {
320 global $wgForceUIMsgAsContentMsg;
321 $args = func_get_args();
322 array_shift( $args );
323 $forcontent = true;
324 if( is_array( $wgForceUIMsgAsContentMsg ) &&
325 in_array( $key, $wgForceUIMsgAsContentMsg ) )
326 $forcontent = false;
327 return wfMsgReal( $key, $args, true, $forcontent );
328 }
329
330 /**
331 * Same as above except doesn't transform the message
332 */
333 function wfMsgForContentNoTrans( $key ) {
334 global $wgForceUIMsgAsContentMsg;
335 $args = func_get_args();
336 array_shift( $args );
337 $forcontent = true;
338 if( is_array( $wgForceUIMsgAsContentMsg ) &&
339 in_array( $key, $wgForceUIMsgAsContentMsg ) )
340 $forcontent = false;
341 return wfMsgReal( $key, $args, true, $forcontent, false );
342 }
343
344 /**
345 * Get a message from the language file, for the UI elements
346 */
347 function wfMsgNoDB( $key ) {
348 $args = func_get_args();
349 array_shift( $args );
350 return wfMsgReal( $key, $args, false );
351 }
352
353 /**
354 * Get a message from the language file, for the content
355 */
356 function wfMsgNoDBForContent( $key ) {
357 global $wgForceUIMsgAsContentMsg;
358 $args = func_get_args();
359 array_shift( $args );
360 $forcontent = true;
361 if( is_array( $wgForceUIMsgAsContentMsg ) &&
362 in_array( $key, $wgForceUIMsgAsContentMsg ) )
363 $forcontent = false;
364 return wfMsgReal( $key, $args, false, $forcontent );
365 }
366
367
368 /**
369 * Really get a message
370 * @param $key String: key to get.
371 * @param $args
372 * @param $useDB Boolean
373 * @param $transform Boolean: Whether or not to transform the message.
374 * @param $forContent Boolean
375 * @return String: the requested message.
376 */
377 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
378 $fname = 'wfMsgReal';
379 wfProfileIn( $fname );
380 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
381 $message = wfMsgReplaceArgs( $message, $args );
382 wfProfileOut( $fname );
383 return $message;
384 }
385
386 /**
387 * This function provides the message source for messages to be edited which are *not* stored in the database.
388 * @param $key String:
389 */
390 function wfMsgWeirdKey ( $key ) {
391 $subsource = str_replace ( ' ' , '_' , $key ) ;
392 $source = wfMsgForContentNoTrans( $subsource ) ;
393 if ( wfEmptyMsg( $subsource, $source) ) {
394 # Try again with first char lower case
395 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
396 $source = wfMsgForContentNoTrans( $subsource ) ;
397 }
398 if ( wfEmptyMsg( $subsource, $source ) ) {
399 # Didn't work either, return blank text
400 $source = "" ;
401 }
402 return $source ;
403 }
404
405 /**
406 * Fetch a message string value, but don't replace any keys yet.
407 * @param string $key
408 * @param bool $useDB
409 * @param bool $forContent
410 * @return string
411 * @private
412 */
413 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
414 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
415
416 if ( is_object( $wgMessageCache ) )
417 $transstat = $wgMessageCache->getTransform();
418
419 if( is_object( $wgMessageCache ) ) {
420 if ( ! $transform )
421 $wgMessageCache->disableTransform();
422 $message = $wgMessageCache->get( $key, $useDB, $forContent );
423 } else {
424 if( $forContent ) {
425 $lang = &$wgContLang;
426 } else {
427 $lang = &$wgLang;
428 }
429
430 wfSuppressWarnings();
431
432 if( is_object( $lang ) ) {
433 $message = $lang->getMessage( $key );
434 } else {
435 $message = false;
436 }
437 wfRestoreWarnings();
438 if($message === false)
439 $message = Language::getMessage($key);
440 if ( $transform && strstr( $message, '{{' ) !== false ) {
441 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
442 }
443 }
444
445 if ( is_object( $wgMessageCache ) && ! $transform )
446 $wgMessageCache->setTransform( $transstat );
447
448 return $message;
449 }
450
451 /**
452 * Replace message parameter keys on the given formatted output.
453 *
454 * @param string $message
455 * @param array $args
456 * @return string
457 * @private
458 */
459 function wfMsgReplaceArgs( $message, $args ) {
460 # Fix windows line-endings
461 # Some messages are split with explode("\n", $msg)
462 $message = str_replace( "\r", '', $message );
463
464 // Replace arguments
465 if ( count( $args ) ) {
466 if ( is_array( $args[0] ) ) {
467 foreach ( $args[0] as $key => $val ) {
468 $message = str_replace( '$' . $key, $val, $message );
469 }
470 } else {
471 foreach( $args as $n => $param ) {
472 $replacementKeys['$' . ($n + 1)] = $param;
473 }
474 $message = strtr( $message, $replacementKeys );
475 }
476 }
477
478 return $message;
479 }
480
481 /**
482 * Return an HTML-escaped version of a message.
483 * Parameter replacements, if any, are done *after* the HTML-escaping,
484 * so parameters may contain HTML (eg links or form controls). Be sure
485 * to pre-escape them if you really do want plaintext, or just wrap
486 * the whole thing in htmlspecialchars().
487 *
488 * @param string $key
489 * @param string ... parameters
490 * @return string
491 */
492 function wfMsgHtml( $key ) {
493 $args = func_get_args();
494 array_shift( $args );
495 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
496 }
497
498 /**
499 * Return an HTML version of message
500 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
501 * so parameters may contain HTML (eg links or form controls). Be sure
502 * to pre-escape them if you really do want plaintext, or just wrap
503 * the whole thing in htmlspecialchars().
504 *
505 * @param string $key
506 * @param string ... parameters
507 * @return string
508 */
509 function wfMsgWikiHtml( $key ) {
510 global $wgOut;
511 $args = func_get_args();
512 array_shift( $args );
513 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
514 }
515
516 /**
517 * Returns message in the requested format
518 * @param string $key Key of the message
519 * @param array $options Processing rules:
520 * <i>parse<i>: parses wikitext to html
521 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
522 * <i>escape<i>: filters message trough htmlspecialchars
523 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
524 * <i>parsemag<i>: ??
525 */
526 function wfMsgExt( $key, $options ) {
527 global $wgOut, $wgParser;
528
529 $args = func_get_args();
530 array_shift( $args );
531 array_shift( $args );
532
533 if( !is_array($options) ) {
534 $options = array($options);
535 }
536
537 $string = wfMsgGetKey( $key, true, false, false );
538
539 if( !in_array('replaceafter', $options) ) {
540 $string = wfMsgReplaceArgs( $string, $args );
541 }
542
543 if( in_array('parse', $options) ) {
544 $string = $wgOut->parse( $string, true, true );
545 } elseif ( in_array('parseinline', $options) ) {
546 $string = $wgOut->parse( $string, true, true );
547 $m = array();
548 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
549 $string = $m[1];
550 }
551 } elseif ( in_array('parsemag', $options) ) {
552 global $wgMessageCache;
553 if ( isset( $wgMessageCache ) ) {
554 $string = $wgMessageCache->transform( $string );
555 }
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 nl2br( 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 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1630 return false;
1631 }
1632 }
1633 return true;
1634 }
1635
1636 /**
1637 * Increment a statistics counter
1638 */
1639 function wfIncrStats( $key ) {
1640 global $wgMemc;
1641 $key = wfMemcKey( 'stats', $key );
1642 if ( is_null( $wgMemc->incr( $key ) ) ) {
1643 $wgMemc->add( $key, 1 );
1644 }
1645 }
1646
1647 /**
1648 * @param mixed $nr The number to format
1649 * @param int $acc The number of digits after the decimal point, default 2
1650 * @param bool $round Whether or not to round the value, default true
1651 * @return float
1652 */
1653 function wfPercent( $nr, $acc = 2, $round = true ) {
1654 $ret = sprintf( "%.${acc}f", $nr );
1655 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1656 }
1657
1658 /**
1659 * Encrypt a username/password.
1660 *
1661 * @param string $userid ID of the user
1662 * @param string $password Password of the user
1663 * @return string Hashed password
1664 */
1665 function wfEncryptPassword( $userid, $password ) {
1666 global $wgPasswordSalt;
1667 $p = md5( $password);
1668
1669 if($wgPasswordSalt)
1670 return md5( "{$userid}-{$p}" );
1671 else
1672 return $p;
1673 }
1674
1675 /**
1676 * Appends to second array if $value differs from that in $default
1677 */
1678 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1679 if ( is_null( $changed ) ) {
1680 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1681 }
1682 if ( $default[$key] !== $value ) {
1683 $changed[$key] = $value;
1684 }
1685 }
1686
1687 /**
1688 * Since wfMsg() and co suck, they don't return false if the message key they
1689 * looked up didn't exist but a XHTML string, this function checks for the
1690 * nonexistance of messages by looking at wfMsg() output
1691 *
1692 * @param $msg The message key looked up
1693 * @param $wfMsgOut The output of wfMsg*()
1694 * @return bool
1695 */
1696 function wfEmptyMsg( $msg, $wfMsgOut ) {
1697 return $wfMsgOut === "&lt;$msg&gt;";
1698 }
1699
1700 /**
1701 * Find out whether or not a mixed variable exists in a string
1702 *
1703 * @param mixed needle
1704 * @param string haystack
1705 * @return bool
1706 */
1707 function in_string( $needle, $str ) {
1708 return strpos( $str, $needle ) !== false;
1709 }
1710
1711 function wfSpecialList( $page, $details ) {
1712 global $wgContLang;
1713 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1714 return $page . $details;
1715 }
1716
1717 /**
1718 * Returns a regular expression of url protocols
1719 *
1720 * @return string
1721 */
1722 function wfUrlProtocols() {
1723 global $wgUrlProtocols;
1724
1725 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1726 // with LocalSettings files from 1.5
1727 if ( is_array( $wgUrlProtocols ) ) {
1728 $protocols = array();
1729 foreach ($wgUrlProtocols as $protocol)
1730 $protocols[] = preg_quote( $protocol, '/' );
1731
1732 return implode( '|', $protocols );
1733 } else {
1734 return $wgUrlProtocols;
1735 }
1736 }
1737
1738 /**
1739 * Execute a shell command, with time and memory limits mirrored from the PHP
1740 * configuration if supported.
1741 * @param $cmd Command line, properly escaped for shell.
1742 * @param &$retval optional, will receive the program's exit code.
1743 * (non-zero is usually failure)
1744 * @return collected stdout as a string (trailing newlines stripped)
1745 */
1746 function wfShellExec( $cmd, &$retval=null ) {
1747 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1748
1749 if( ini_get( 'safe_mode' ) ) {
1750 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1751 $retval = 1;
1752 return "Unable to run external programs in safe mode.";
1753 }
1754
1755 if ( php_uname( 's' ) == 'Linux' ) {
1756 $time = ini_get( 'max_execution_time' );
1757 $mem = intval( $wgMaxShellMemory );
1758 $filesize = intval( $wgMaxShellFileSize );
1759
1760 if ( $time > 0 && $mem > 0 ) {
1761 $script = "$IP/bin/ulimit-tvf.sh";
1762 if ( is_executable( $script ) ) {
1763 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1764 }
1765 }
1766 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1767 # This is a hack to work around PHP's flawed invocation of cmd.exe
1768 # http://news.php.net/php.internals/21796
1769 $cmd = '"' . $cmd . '"';
1770 }
1771 wfDebug( "wfShellExec: $cmd\n" );
1772
1773 $output = array();
1774 $retval = 1; // error by default?
1775 exec( $cmd, $output, $retval ); // returns the last line of output.
1776 return implode( "\n", $output );
1777
1778 }
1779
1780 /**
1781 * This function works like "use VERSION" in Perl, the program will die with a
1782 * backtrace if the current version of PHP is less than the version provided
1783 *
1784 * This is useful for extensions which due to their nature are not kept in sync
1785 * with releases, and might depend on other versions of PHP than the main code
1786 *
1787 * Note: PHP might die due to parsing errors in some cases before it ever
1788 * manages to call this function, such is life
1789 *
1790 * @see perldoc -f use
1791 *
1792 * @param mixed $version The version to check, can be a string, an integer, or
1793 * a float
1794 */
1795 function wfUsePHP( $req_ver ) {
1796 $php_ver = PHP_VERSION;
1797
1798 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1799 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1800 }
1801
1802 /**
1803 * This function works like "use VERSION" in Perl except it checks the version
1804 * of MediaWiki, the program will die with a backtrace if the current version
1805 * of MediaWiki is less than the version provided.
1806 *
1807 * This is useful for extensions which due to their nature are not kept in sync
1808 * with releases
1809 *
1810 * @see perldoc -f use
1811 *
1812 * @param mixed $version The version to check, can be a string, an integer, or
1813 * a float
1814 */
1815 function wfUseMW( $req_ver ) {
1816 global $wgVersion;
1817
1818 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1819 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1820 }
1821
1822 /**
1823 * @deprecated use StringUtils::escapeRegexReplacement
1824 */
1825 function wfRegexReplacement( $string ) {
1826 return StringUtils::escapeRegexReplacement( $string );
1827 }
1828
1829 /**
1830 * Return the final portion of a pathname.
1831 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1832 * http://bugs.php.net/bug.php?id=33898
1833 *
1834 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1835 * We'll consider it so always, as we don't want \s in our Unix paths either.
1836 *
1837 * @param string $path
1838 * @return string
1839 */
1840 function wfBaseName( $path ) {
1841 $matches = array();
1842 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1843 return $matches[1];
1844 } else {
1845 return '';
1846 }
1847 }
1848
1849 /**
1850 * Generate a relative path name to the given file.
1851 * May explode on non-matching case-insensitive paths,
1852 * funky symlinks, etc.
1853 *
1854 * @param string $path Absolute destination path including target filename
1855 * @param string $from Absolute source path, directory only
1856 * @return string
1857 */
1858 function wfRelativePath( $path, $from ) {
1859 // Normalize mixed input on Windows...
1860 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1861 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1862
1863 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1864 $against = explode( DIRECTORY_SEPARATOR, $from );
1865
1866 // Trim off common prefix
1867 while( count( $pieces ) && count( $against )
1868 && $pieces[0] == $against[0] ) {
1869 array_shift( $pieces );
1870 array_shift( $against );
1871 }
1872
1873 // relative dots to bump us to the parent
1874 while( count( $against ) ) {
1875 array_unshift( $pieces, '..' );
1876 array_shift( $against );
1877 }
1878
1879 array_push( $pieces, wfBaseName( $path ) );
1880
1881 return implode( DIRECTORY_SEPARATOR, $pieces );
1882 }
1883
1884 /**
1885 * Make a URL index, appropriate for the el_index field of externallinks.
1886 */
1887 function wfMakeUrlIndex( $url ) {
1888 wfSuppressWarnings();
1889 $bits = parse_url( $url );
1890 wfRestoreWarnings();
1891 if ( !$bits || $bits['scheme'] !== 'http' ) {
1892 return false;
1893 }
1894 // Reverse the labels in the hostname, convert to lower case
1895 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1896 // Add an extra dot to the end
1897 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1898 $reversedHost .= '.';
1899 }
1900 // Reconstruct the pseudo-URL
1901 $index = "http://$reversedHost";
1902 // Leave out user and password. Add the port, path, query and fragment
1903 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1904 if ( isset( $bits['path'] ) ) {
1905 $index .= $bits['path'];
1906 } else {
1907 $index .= '/';
1908 }
1909 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1910 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1911 return $index;
1912 }
1913
1914 /**
1915 * Do any deferred updates and clear the list
1916 * TODO: This could be in Wiki.php if that class made any sense at all
1917 */
1918 function wfDoUpdates()
1919 {
1920 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1921 foreach ( $wgDeferredUpdateList as $update ) {
1922 $update->doUpdate();
1923 }
1924 foreach ( $wgPostCommitUpdateList as $update ) {
1925 $update->doUpdate();
1926 }
1927 $wgDeferredUpdateList = array();
1928 $wgPostCommitUpdateList = array();
1929 }
1930
1931 /**
1932 * @deprecated use StringUtils::explodeMarkup
1933 */
1934 function wfExplodeMarkup( $separator, $text ) {
1935 return StringUtils::explodeMarkup( $separator, $text );
1936 }
1937
1938 /**
1939 * Convert an arbitrarily-long digit string from one numeric base
1940 * to another, optionally zero-padding to a minimum column width.
1941 *
1942 * Supports base 2 through 36; digit values 10-36 are represented
1943 * as lowercase letters a-z. Input is case-insensitive.
1944 *
1945 * @param $input string of digits
1946 * @param $sourceBase int 2-36
1947 * @param $destBase int 2-36
1948 * @param $pad int 1 or greater
1949 * @return string or false on invalid input
1950 */
1951 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1952 if( $sourceBase < 2 ||
1953 $sourceBase > 36 ||
1954 $destBase < 2 ||
1955 $destBase > 36 ||
1956 $pad < 1 ||
1957 $sourceBase != intval( $sourceBase ) ||
1958 $destBase != intval( $destBase ) ||
1959 $pad != intval( $pad ) ||
1960 !is_string( $input ) ||
1961 $input == '' ) {
1962 return false;
1963 }
1964
1965 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1966 $inDigits = array();
1967 $outChars = '';
1968
1969 // Decode and validate input string
1970 $input = strtolower( $input );
1971 for( $i = 0; $i < strlen( $input ); $i++ ) {
1972 $n = strpos( $digitChars, $input{$i} );
1973 if( $n === false || $n > $sourceBase ) {
1974 return false;
1975 }
1976 $inDigits[] = $n;
1977 }
1978
1979 // Iterate over the input, modulo-ing out an output digit
1980 // at a time until input is gone.
1981 while( count( $inDigits ) ) {
1982 $work = 0;
1983 $workDigits = array();
1984
1985 // Long division...
1986 foreach( $inDigits as $digit ) {
1987 $work *= $sourceBase;
1988 $work += $digit;
1989
1990 if( $work < $destBase ) {
1991 // Gonna need to pull another digit.
1992 if( count( $workDigits ) ) {
1993 // Avoid zero-padding; this lets us find
1994 // the end of the input very easily when
1995 // length drops to zero.
1996 $workDigits[] = 0;
1997 }
1998 } else {
1999 // Finally! Actual division!
2000 $workDigits[] = intval( $work / $destBase );
2001
2002 // Isn't it annoying that most programming languages
2003 // don't have a single divide-and-remainder operator,
2004 // even though the CPU implements it that way?
2005 $work = $work % $destBase;
2006 }
2007 }
2008
2009 // All that division leaves us with a remainder,
2010 // which is conveniently our next output digit.
2011 $outChars .= $digitChars[$work];
2012
2013 // And we continue!
2014 $inDigits = $workDigits;
2015 }
2016
2017 while( strlen( $outChars ) < $pad ) {
2018 $outChars .= '0';
2019 }
2020
2021 return strrev( $outChars );
2022 }
2023
2024 /**
2025 * Create an object with a given name and an array of construct parameters
2026 * @param string $name
2027 * @param array $p parameters
2028 */
2029 function wfCreateObject( $name, $p ){
2030 $p = array_values( $p );
2031 switch ( count( $p ) ) {
2032 case 0:
2033 return new $name;
2034 case 1:
2035 return new $name( $p[0] );
2036 case 2:
2037 return new $name( $p[0], $p[1] );
2038 case 3:
2039 return new $name( $p[0], $p[1], $p[2] );
2040 case 4:
2041 return new $name( $p[0], $p[1], $p[2], $p[3] );
2042 case 5:
2043 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2044 case 6:
2045 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2046 default:
2047 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2048 }
2049 }
2050
2051 /**
2052 * Aliases for modularized functions
2053 */
2054 function wfGetHTTP( $url, $timeout = 'default' ) {
2055 return Http::get( $url, $timeout );
2056 }
2057 function wfIsLocalURL( $url ) {
2058 return Http::isLocalURL( $url );
2059 }
2060
2061 /**
2062 * Initialise php session
2063 */
2064 function wfSetupSession() {
2065 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
2066 if( $wgSessionsInMemcached ) {
2067 require_once( 'MemcachedSessions.php' );
2068 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2069 # If it's left on 'user' or another setting from another
2070 # application, it will end up failing. Try to recover.
2071 ini_set ( 'session.save_handler', 'files' );
2072 }
2073 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
2074 session_cache_limiter( 'private, must-revalidate' );
2075 @session_start();
2076 }
2077
2078 /**
2079 * Get an object from the precompiled serialized directory
2080 *
2081 * @return mixed The variable on success, false on failure
2082 */
2083 function wfGetPrecompiledData( $name ) {
2084 global $IP;
2085
2086 $file = "$IP/serialized/$name";
2087 if ( file_exists( $file ) ) {
2088 $blob = file_get_contents( $file );
2089 if ( $blob ) {
2090 return unserialize( $blob );
2091 }
2092 }
2093 return false;
2094 }
2095
2096 function wfGetCaller( $level = 2 ) {
2097 $backtrace = wfDebugBacktrace();
2098 if ( isset( $backtrace[$level] ) ) {
2099 if ( isset( $backtrace[$level]['class'] ) ) {
2100 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2101 } else {
2102 $caller = $backtrace[$level]['function'];
2103 }
2104 } else {
2105 $caller = 'unknown';
2106 }
2107 return $caller;
2108 }
2109
2110 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2111 function wfGetAllCallers() {
2112 return implode('/', array_map(
2113 create_function('$frame','
2114 return isset( $frame["class"] )?
2115 $frame["class"]."::".$frame["function"]:
2116 $frame["function"];
2117 '),
2118 array_reverse(wfDebugBacktrace())));
2119 }
2120
2121 /**
2122 * Get a cache key
2123 */
2124 function wfMemcKey( /*... */ ) {
2125 global $wgDBprefix, $wgDBname;
2126 $args = func_get_args();
2127 if ( $wgDBprefix ) {
2128 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2129 } else {
2130 $key = $wgDBname . ':' . implode( ':', $args );
2131 }
2132 return $key;
2133 }
2134
2135 /**
2136 * Get a cache key for a foreign DB
2137 */
2138 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2139 $args = array_slice( func_get_args(), 2 );
2140 if ( $prefix ) {
2141 $key = "$db-$prefix:" . implode( ':', $args );
2142 } else {
2143 $key = $db . ':' . implode( ':', $args );
2144 }
2145 return $key;
2146 }
2147
2148 /**
2149 * Get an ASCII string identifying this wiki
2150 * This is used as a prefix in memcached keys
2151 */
2152 function wfWikiID() {
2153 global $wgDBprefix, $wgDBname;
2154 if ( $wgDBprefix ) {
2155 return "$wgDBname-$wgDBprefix";
2156 } else {
2157 return $wgDBname;
2158 }
2159 }
2160
2161 /*
2162 * Get a Database object
2163 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2164 * master (for write queries), DB_SLAVE for potentially lagged
2165 * read queries, or an integer >= 0 for a particular server.
2166 *
2167 * @param mixed $groups Query groups. An array of group names that this query
2168 * belongs to. May contain a single string if the query is only
2169 * in one group.
2170 */
2171 function &wfGetDB( $db = DB_LAST, $groups = array() ) {
2172 global $wgLoadBalancer;
2173 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2174 return $ret;
2175 }
2176 ?>