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