Erase the Content-Encoding and Content-Length for the new output buffer/compression...
[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 wfMsg( 'showingresults', $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 wfMsg( 'showingresultsnum', $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' );
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 while( $status = ob_get_status() ) {
1118 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1119 // Probably from zlib.output_compression or other
1120 // PHP-internal setting which can't be removed.
1121 //
1122 // Give up, and hope the result doesn't break
1123 // output behavior.
1124 break;
1125 }
1126 if( !ob_end_clean() ) {
1127 // Could not remove output buffer handler; abort now
1128 // to avoid getting in some kind of infinite loop.
1129 break;
1130 }
1131 if( $resetGzipEncoding ) {
1132 if( $status['name'] == 'ob_gzhandler' ) {
1133 // Reset the 'Content-Encoding' field set by this handler
1134 // so we can start fresh.
1135 header( 'Content-Encoding:' );
1136 }
1137 if( $status['name'] == 'wfOutputHandler' ) {
1138 // And the custom handler in 1.10+ adds a Content-Length
1139 header( 'Content-Encoding:' );
1140 header( 'Content-Length:' );
1141 }
1142 }
1143 }
1144 }
1145
1146 /**
1147 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1148 *
1149 * Clear away output buffers, but keep the Content-Encoding header
1150 * produced by ob_gzhandler, if any.
1151 *
1152 * This should be used for HTTP 304 responses, where you need to
1153 * preserve the Content-Encoding header of the real result, but
1154 * also need to suppress the output of ob_gzhandler to keep to spec
1155 * and avoid breaking Firefox in rare cases where the headers and
1156 * body are broken over two packets.
1157 */
1158 function wfClearOutputBuffers() {
1159 wfResetOutputBuffers( false );
1160 }
1161
1162 /**
1163 * Converts an Accept-* header into an array mapping string values to quality
1164 * factors
1165 */
1166 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1167 # No arg means accept anything (per HTTP spec)
1168 if( !$accept ) {
1169 return array( $def => 1 );
1170 }
1171
1172 $prefs = array();
1173
1174 $parts = explode( ',', $accept );
1175
1176 foreach( $parts as $part ) {
1177 # FIXME: doesn't deal with params like 'text/html; level=1'
1178 @list( $value, $qpart ) = explode( ';', $part );
1179 $match = array();
1180 if( !isset( $qpart ) ) {
1181 $prefs[$value] = 1;
1182 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1183 $prefs[$value] = $match[1];
1184 }
1185 }
1186
1187 return $prefs;
1188 }
1189
1190 /**
1191 * Checks if a given MIME type matches any of the keys in the given
1192 * array. Basic wildcards are accepted in the array keys.
1193 *
1194 * Returns the matching MIME type (or wildcard) if a match, otherwise
1195 * NULL if no match.
1196 *
1197 * @param string $type
1198 * @param array $avail
1199 * @return string
1200 * @private
1201 */
1202 function mimeTypeMatch( $type, $avail ) {
1203 if( array_key_exists($type, $avail) ) {
1204 return $type;
1205 } else {
1206 $parts = explode( '/', $type );
1207 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1208 return $parts[0] . '/*';
1209 } elseif( array_key_exists( '*/*', $avail ) ) {
1210 return '*/*';
1211 } else {
1212 return NULL;
1213 }
1214 }
1215 }
1216
1217 /**
1218 * Returns the 'best' match between a client's requested internet media types
1219 * and the server's list of available types. Each list should be an associative
1220 * array of type to preference (preference is a float between 0.0 and 1.0).
1221 * Wildcards in the types are acceptable.
1222 *
1223 * @param array $cprefs Client's acceptable type list
1224 * @param array $sprefs Server's offered types
1225 * @return string
1226 *
1227 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1228 * XXX: generalize to negotiate other stuff
1229 */
1230 function wfNegotiateType( $cprefs, $sprefs ) {
1231 $combine = array();
1232
1233 foreach( array_keys($sprefs) as $type ) {
1234 $parts = explode( '/', $type );
1235 if( $parts[1] != '*' ) {
1236 $ckey = mimeTypeMatch( $type, $cprefs );
1237 if( $ckey ) {
1238 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1239 }
1240 }
1241 }
1242
1243 foreach( array_keys( $cprefs ) as $type ) {
1244 $parts = explode( '/', $type );
1245 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1246 $skey = mimeTypeMatch( $type, $sprefs );
1247 if( $skey ) {
1248 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1249 }
1250 }
1251 }
1252
1253 $bestq = 0;
1254 $besttype = NULL;
1255
1256 foreach( array_keys( $combine ) as $type ) {
1257 if( $combine[$type] > $bestq ) {
1258 $besttype = $type;
1259 $bestq = $combine[$type];
1260 }
1261 }
1262
1263 return $besttype;
1264 }
1265
1266 /**
1267 * Array lookup
1268 * Returns an array where the values in the first array are replaced by the
1269 * values in the second array with the corresponding keys
1270 *
1271 * @return array
1272 */
1273 function wfArrayLookup( $a, $b ) {
1274 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1275 }
1276
1277 /**
1278 * Convenience function; returns MediaWiki timestamp for the present time.
1279 * @return string
1280 */
1281 function wfTimestampNow() {
1282 # return NOW
1283 return wfTimestamp( TS_MW, time() );
1284 }
1285
1286 /**
1287 * Reference-counted warning suppression
1288 */
1289 function wfSuppressWarnings( $end = false ) {
1290 static $suppressCount = 0;
1291 static $originalLevel = false;
1292
1293 if ( $end ) {
1294 if ( $suppressCount ) {
1295 --$suppressCount;
1296 if ( !$suppressCount ) {
1297 error_reporting( $originalLevel );
1298 }
1299 }
1300 } else {
1301 if ( !$suppressCount ) {
1302 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1303 }
1304 ++$suppressCount;
1305 }
1306 }
1307
1308 /**
1309 * Restore error level to previous value
1310 */
1311 function wfRestoreWarnings() {
1312 wfSuppressWarnings( true );
1313 }
1314
1315 # Autodetect, convert and provide timestamps of various types
1316
1317 /**
1318 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1319 */
1320 define('TS_UNIX', 0);
1321
1322 /**
1323 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1324 */
1325 define('TS_MW', 1);
1326
1327 /**
1328 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1329 */
1330 define('TS_DB', 2);
1331
1332 /**
1333 * RFC 2822 format, for E-mail and HTTP headers
1334 */
1335 define('TS_RFC2822', 3);
1336
1337 /**
1338 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1339 *
1340 * This is used by Special:Export
1341 */
1342 define('TS_ISO_8601', 4);
1343
1344 /**
1345 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1346 *
1347 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1348 * DateTime tag and page 36 for the DateTimeOriginal and
1349 * DateTimeDigitized tags.
1350 */
1351 define('TS_EXIF', 5);
1352
1353 /**
1354 * Oracle format time.
1355 */
1356 define('TS_ORACLE', 6);
1357
1358 /**
1359 * Postgres format time.
1360 */
1361 define('TS_POSTGRES', 7);
1362
1363 /**
1364 * @param mixed $outputtype A timestamp in one of the supported formats, the
1365 * function will autodetect which format is supplied
1366 * and act accordingly.
1367 * @return string Time in the format specified in $outputtype
1368 */
1369 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1370 $uts = 0;
1371 $da = array();
1372 if ($ts==0) {
1373 $uts=time();
1374 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1375 # TS_DB
1376 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1377 (int)$da[2],(int)$da[3],(int)$da[1]);
1378 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1379 # TS_EXIF
1380 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1381 (int)$da[2],(int)$da[3],(int)$da[1]);
1382 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1383 # TS_MW
1384 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1385 (int)$da[2],(int)$da[3],(int)$da[1]);
1386 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1387 # TS_UNIX
1388 $uts = $ts;
1389 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1390 # TS_ORACLE
1391 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1392 str_replace("+00:00", "UTC", $ts)));
1393 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1394 # TS_ISO_8601
1395 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1396 (int)$da[2],(int)$da[3],(int)$da[1]);
1397 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1398 # TS_POSTGRES
1399 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1400 (int)$da[2],(int)$da[3],(int)$da[1]);
1401 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1402 # TS_POSTGRES
1403 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1404 (int)$da[2],(int)$da[3],(int)$da[1]);
1405 } else {
1406 # Bogus value; fall back to the epoch...
1407 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1408 $uts = 0;
1409 }
1410
1411
1412 switch($outputtype) {
1413 case TS_UNIX:
1414 return $uts;
1415 case TS_MW:
1416 return gmdate( 'YmdHis', $uts );
1417 case TS_DB:
1418 return gmdate( 'Y-m-d H:i:s', $uts );
1419 case TS_ISO_8601:
1420 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1421 // This shouldn't ever be used, but is included for completeness
1422 case TS_EXIF:
1423 return gmdate( 'Y:m:d H:i:s', $uts );
1424 case TS_RFC2822:
1425 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1426 case TS_ORACLE:
1427 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1428 case TS_POSTGRES:
1429 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1430 default:
1431 throw new MWException( 'wfTimestamp() called with illegal output type.');
1432 }
1433 }
1434
1435 /**
1436 * Return a formatted timestamp, or null if input is null.
1437 * For dealing with nullable timestamp columns in the database.
1438 * @param int $outputtype
1439 * @param string $ts
1440 * @return string
1441 */
1442 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1443 if( is_null( $ts ) ) {
1444 return null;
1445 } else {
1446 return wfTimestamp( $outputtype, $ts );
1447 }
1448 }
1449
1450 /**
1451 * Check if the operating system is Windows
1452 *
1453 * @return bool True if it's Windows, False otherwise.
1454 */
1455 function wfIsWindows() {
1456 if (substr(php_uname(), 0, 7) == 'Windows') {
1457 return true;
1458 } else {
1459 return false;
1460 }
1461 }
1462
1463 /**
1464 * Swap two variables
1465 */
1466 function swap( &$x, &$y ) {
1467 $z = $x;
1468 $x = $y;
1469 $y = $z;
1470 }
1471
1472 function wfGetCachedNotice( $name ) {
1473 global $wgOut, $parserMemc;
1474 $fname = 'wfGetCachedNotice';
1475 wfProfileIn( $fname );
1476
1477 $needParse = false;
1478
1479 if( $name === 'default' ) {
1480 // special case
1481 global $wgSiteNotice;
1482 $notice = $wgSiteNotice;
1483 if( empty( $notice ) ) {
1484 wfProfileOut( $fname );
1485 return false;
1486 }
1487 } else {
1488 $notice = wfMsgForContentNoTrans( $name );
1489 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1490 wfProfileOut( $fname );
1491 return( false );
1492 }
1493 }
1494
1495 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1496 if( is_array( $cachedNotice ) ) {
1497 if( md5( $notice ) == $cachedNotice['hash'] ) {
1498 $notice = $cachedNotice['html'];
1499 } else {
1500 $needParse = true;
1501 }
1502 } else {
1503 $needParse = true;
1504 }
1505
1506 if( $needParse ) {
1507 if( is_object( $wgOut ) ) {
1508 $parsed = $wgOut->parse( $notice );
1509 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1510 $notice = $parsed;
1511 } else {
1512 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1513 $notice = '';
1514 }
1515 }
1516
1517 wfProfileOut( $fname );
1518 return $notice;
1519 }
1520
1521 function wfGetNamespaceNotice() {
1522 global $wgTitle;
1523
1524 # Paranoia
1525 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1526 return "";
1527
1528 $fname = 'wfGetNamespaceNotice';
1529 wfProfileIn( $fname );
1530
1531 $key = "namespacenotice-" . $wgTitle->getNsText();
1532 $namespaceNotice = wfGetCachedNotice( $key );
1533 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1534 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1535 } else {
1536 $namespaceNotice = "";
1537 }
1538
1539 wfProfileOut( $fname );
1540 return $namespaceNotice;
1541 }
1542
1543 function wfGetSiteNotice() {
1544 global $wgUser, $wgSiteNotice;
1545 $fname = 'wfGetSiteNotice';
1546 wfProfileIn( $fname );
1547 $siteNotice = '';
1548
1549 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1550 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1551 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1552 } else {
1553 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1554 if( !$anonNotice ) {
1555 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1556 } else {
1557 $siteNotice = $anonNotice;
1558 }
1559 }
1560 if( !$siteNotice ) {
1561 $siteNotice = wfGetCachedNotice( 'default' );
1562 }
1563 }
1564
1565 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1566 wfProfileOut( $fname );
1567 return $siteNotice;
1568 }
1569
1570 /**
1571 * BC wrapper for MimeMagic::singleton()
1572 * @deprecated
1573 */
1574 function &wfGetMimeMagic() {
1575 return MimeMagic::singleton();
1576 }
1577
1578 /**
1579 * Tries to get the system directory for temporary files.
1580 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1581 * and if none are set /tmp is returned as the generic Unix default.
1582 *
1583 * NOTE: When possible, use the tempfile() function to create temporary
1584 * files to avoid race conditions on file creation, etc.
1585 *
1586 * @return string
1587 */
1588 function wfTempDir() {
1589 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1590 $tmp = getenv( $var );
1591 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1592 return $tmp;
1593 }
1594 }
1595 # Hope this is Unix of some kind!
1596 return '/tmp';
1597 }
1598
1599 /**
1600 * Make directory, and make all parent directories if they don't exist
1601 */
1602 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1603 if ( strval( $fullDir ) === '' ) {
1604 return true;
1605 }
1606
1607 # Go back through the paths to find the first directory that exists
1608 $currentDir = $fullDir;
1609 $createList = array();
1610 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1611 # Strip trailing slashes
1612 $currentDir = rtrim( $currentDir, '/\\' );
1613
1614 # Add to create list
1615 $createList[] = $currentDir;
1616
1617 # Find next delimiter searching from the end
1618 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1619 if ( $p === false ) {
1620 $currentDir = false;
1621 } else {
1622 $currentDir = substr( $currentDir, 0, $p );
1623 }
1624 }
1625
1626 if ( count( $createList ) == 0 ) {
1627 # Directory specified already exists
1628 return true;
1629 } elseif ( $currentDir === false ) {
1630 # Went all the way back to root and it apparently doesn't exist
1631 return false;
1632 }
1633
1634 # Now go forward creating directories
1635 $createList = array_reverse( $createList );
1636 foreach ( $createList as $dir ) {
1637 # use chmod to override the umask, as suggested by the PHP manual
1638 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1639 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1640 return false;
1641 }
1642 }
1643 return true;
1644 }
1645
1646 /**
1647 * Increment a statistics counter
1648 */
1649 function wfIncrStats( $key ) {
1650 global $wgMemc;
1651 $key = wfMemcKey( 'stats', $key );
1652 if ( is_null( $wgMemc->incr( $key ) ) ) {
1653 $wgMemc->add( $key, 1 );
1654 }
1655 }
1656
1657 /**
1658 * @param mixed $nr The number to format
1659 * @param int $acc The number of digits after the decimal point, default 2
1660 * @param bool $round Whether or not to round the value, default true
1661 * @return float
1662 */
1663 function wfPercent( $nr, $acc = 2, $round = true ) {
1664 $ret = sprintf( "%.${acc}f", $nr );
1665 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1666 }
1667
1668 /**
1669 * Encrypt a username/password.
1670 *
1671 * @param string $userid ID of the user
1672 * @param string $password Password of the user
1673 * @return string Hashed password
1674 */
1675 function wfEncryptPassword( $userid, $password ) {
1676 global $wgPasswordSalt;
1677 $p = md5( $password);
1678
1679 if($wgPasswordSalt)
1680 return md5( "{$userid}-{$p}" );
1681 else
1682 return $p;
1683 }
1684
1685 /**
1686 * Appends to second array if $value differs from that in $default
1687 */
1688 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1689 if ( is_null( $changed ) ) {
1690 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1691 }
1692 if ( $default[$key] !== $value ) {
1693 $changed[$key] = $value;
1694 }
1695 }
1696
1697 /**
1698 * Since wfMsg() and co suck, they don't return false if the message key they
1699 * looked up didn't exist but a XHTML string, this function checks for the
1700 * nonexistance of messages by looking at wfMsg() output
1701 *
1702 * @param $msg The message key looked up
1703 * @param $wfMsgOut The output of wfMsg*()
1704 * @return bool
1705 */
1706 function wfEmptyMsg( $msg, $wfMsgOut ) {
1707 return $wfMsgOut === "&lt;$msg&gt;";
1708 }
1709
1710 /**
1711 * Find out whether or not a mixed variable exists in a string
1712 *
1713 * @param mixed needle
1714 * @param string haystack
1715 * @return bool
1716 */
1717 function in_string( $needle, $str ) {
1718 return strpos( $str, $needle ) !== false;
1719 }
1720
1721 function wfSpecialList( $page, $details ) {
1722 global $wgContLang;
1723 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1724 return $page . $details;
1725 }
1726
1727 /**
1728 * Returns a regular expression of url protocols
1729 *
1730 * @return string
1731 */
1732 function wfUrlProtocols() {
1733 global $wgUrlProtocols;
1734
1735 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1736 // with LocalSettings files from 1.5
1737 if ( is_array( $wgUrlProtocols ) ) {
1738 $protocols = array();
1739 foreach ($wgUrlProtocols as $protocol)
1740 $protocols[] = preg_quote( $protocol, '/' );
1741
1742 return implode( '|', $protocols );
1743 } else {
1744 return $wgUrlProtocols;
1745 }
1746 }
1747
1748 /**
1749 * Execute a shell command, with time and memory limits mirrored from the PHP
1750 * configuration if supported.
1751 * @param $cmd Command line, properly escaped for shell.
1752 * @param &$retval optional, will receive the program's exit code.
1753 * (non-zero is usually failure)
1754 * @return collected stdout as a string (trailing newlines stripped)
1755 */
1756 function wfShellExec( $cmd, &$retval=null ) {
1757 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1758
1759 if( ini_get( 'safe_mode' ) ) {
1760 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1761 $retval = 1;
1762 return "Unable to run external programs in safe mode.";
1763 }
1764
1765 if ( php_uname( 's' ) == 'Linux' ) {
1766 $time = ini_get( 'max_execution_time' );
1767 $mem = intval( $wgMaxShellMemory );
1768 $filesize = intval( $wgMaxShellFileSize );
1769
1770 if ( $time > 0 && $mem > 0 ) {
1771 $script = "$IP/bin/ulimit-tvf.sh";
1772 if ( is_executable( $script ) ) {
1773 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1774 }
1775 }
1776 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1777 # This is a hack to work around PHP's flawed invocation of cmd.exe
1778 # http://news.php.net/php.internals/21796
1779 $cmd = '"' . $cmd . '"';
1780 }
1781 wfDebug( "wfShellExec: $cmd\n" );
1782
1783 $output = array();
1784 $retval = 1; // error by default?
1785 exec( $cmd, $output, $retval ); // returns the last line of output.
1786 return implode( "\n", $output );
1787
1788 }
1789
1790 /**
1791 * This function works like "use VERSION" in Perl, the program will die with a
1792 * backtrace if the current version of PHP is less than the version provided
1793 *
1794 * This is useful for extensions which due to their nature are not kept in sync
1795 * with releases, and might depend on other versions of PHP than the main code
1796 *
1797 * Note: PHP might die due to parsing errors in some cases before it ever
1798 * manages to call this function, such is life
1799 *
1800 * @see perldoc -f use
1801 *
1802 * @param mixed $version The version to check, can be a string, an integer, or
1803 * a float
1804 */
1805 function wfUsePHP( $req_ver ) {
1806 $php_ver = PHP_VERSION;
1807
1808 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1809 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1810 }
1811
1812 /**
1813 * This function works like "use VERSION" in Perl except it checks the version
1814 * of MediaWiki, the program will die with a backtrace if the current version
1815 * of MediaWiki is less than the version provided.
1816 *
1817 * This is useful for extensions which due to their nature are not kept in sync
1818 * with releases
1819 *
1820 * @see perldoc -f use
1821 *
1822 * @param mixed $version The version to check, can be a string, an integer, or
1823 * a float
1824 */
1825 function wfUseMW( $req_ver ) {
1826 global $wgVersion;
1827
1828 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1829 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1830 }
1831
1832 /**
1833 * @deprecated use StringUtils::escapeRegexReplacement
1834 */
1835 function wfRegexReplacement( $string ) {
1836 return StringUtils::escapeRegexReplacement( $string );
1837 }
1838
1839 /**
1840 * Return the final portion of a pathname.
1841 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1842 * http://bugs.php.net/bug.php?id=33898
1843 *
1844 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1845 * We'll consider it so always, as we don't want \s in our Unix paths either.
1846 *
1847 * @param string $path
1848 * @return string
1849 */
1850 function wfBaseName( $path ) {
1851 $matches = array();
1852 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1853 return $matches[1];
1854 } else {
1855 return '';
1856 }
1857 }
1858
1859 /**
1860 * Generate a relative path name to the given file.
1861 * May explode on non-matching case-insensitive paths,
1862 * funky symlinks, etc.
1863 *
1864 * @param string $path Absolute destination path including target filename
1865 * @param string $from Absolute source path, directory only
1866 * @return string
1867 */
1868 function wfRelativePath( $path, $from ) {
1869 // Normalize mixed input on Windows...
1870 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1871 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1872
1873 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1874 $against = explode( DIRECTORY_SEPARATOR, $from );
1875
1876 // Trim off common prefix
1877 while( count( $pieces ) && count( $against )
1878 && $pieces[0] == $against[0] ) {
1879 array_shift( $pieces );
1880 array_shift( $against );
1881 }
1882
1883 // relative dots to bump us to the parent
1884 while( count( $against ) ) {
1885 array_unshift( $pieces, '..' );
1886 array_shift( $against );
1887 }
1888
1889 array_push( $pieces, wfBaseName( $path ) );
1890
1891 return implode( DIRECTORY_SEPARATOR, $pieces );
1892 }
1893
1894 /**
1895 * Make a URL index, appropriate for the el_index field of externallinks.
1896 */
1897 function wfMakeUrlIndex( $url ) {
1898 wfSuppressWarnings();
1899 $bits = parse_url( $url );
1900 wfRestoreWarnings();
1901 if ( !$bits || $bits['scheme'] !== 'http' ) {
1902 return false;
1903 }
1904 // Reverse the labels in the hostname, convert to lower case
1905 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1906 // Add an extra dot to the end
1907 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1908 $reversedHost .= '.';
1909 }
1910 // Reconstruct the pseudo-URL
1911 $index = "http://$reversedHost";
1912 // Leave out user and password. Add the port, path, query and fragment
1913 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1914 if ( isset( $bits['path'] ) ) {
1915 $index .= $bits['path'];
1916 } else {
1917 $index .= '/';
1918 }
1919 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1920 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1921 return $index;
1922 }
1923
1924 /**
1925 * Do any deferred updates and clear the list
1926 * TODO: This could be in Wiki.php if that class made any sense at all
1927 */
1928 function wfDoUpdates()
1929 {
1930 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1931 foreach ( $wgDeferredUpdateList as $update ) {
1932 $update->doUpdate();
1933 }
1934 foreach ( $wgPostCommitUpdateList as $update ) {
1935 $update->doUpdate();
1936 }
1937 $wgDeferredUpdateList = array();
1938 $wgPostCommitUpdateList = array();
1939 }
1940
1941 /**
1942 * @deprecated use StringUtils::explodeMarkup
1943 */
1944 function wfExplodeMarkup( $separator, $text ) {
1945 return StringUtils::explodeMarkup( $separator, $text );
1946 }
1947
1948 /**
1949 * Convert an arbitrarily-long digit string from one numeric base
1950 * to another, optionally zero-padding to a minimum column width.
1951 *
1952 * Supports base 2 through 36; digit values 10-36 are represented
1953 * as lowercase letters a-z. Input is case-insensitive.
1954 *
1955 * @param $input string of digits
1956 * @param $sourceBase int 2-36
1957 * @param $destBase int 2-36
1958 * @param $pad int 1 or greater
1959 * @return string or false on invalid input
1960 */
1961 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1962 if( $sourceBase < 2 ||
1963 $sourceBase > 36 ||
1964 $destBase < 2 ||
1965 $destBase > 36 ||
1966 $pad < 1 ||
1967 $sourceBase != intval( $sourceBase ) ||
1968 $destBase != intval( $destBase ) ||
1969 $pad != intval( $pad ) ||
1970 !is_string( $input ) ||
1971 $input == '' ) {
1972 return false;
1973 }
1974
1975 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1976 $inDigits = array();
1977 $outChars = '';
1978
1979 // Decode and validate input string
1980 $input = strtolower( $input );
1981 for( $i = 0; $i < strlen( $input ); $i++ ) {
1982 $n = strpos( $digitChars, $input{$i} );
1983 if( $n === false || $n > $sourceBase ) {
1984 return false;
1985 }
1986 $inDigits[] = $n;
1987 }
1988
1989 // Iterate over the input, modulo-ing out an output digit
1990 // at a time until input is gone.
1991 while( count( $inDigits ) ) {
1992 $work = 0;
1993 $workDigits = array();
1994
1995 // Long division...
1996 foreach( $inDigits as $digit ) {
1997 $work *= $sourceBase;
1998 $work += $digit;
1999
2000 if( $work < $destBase ) {
2001 // Gonna need to pull another digit.
2002 if( count( $workDigits ) ) {
2003 // Avoid zero-padding; this lets us find
2004 // the end of the input very easily when
2005 // length drops to zero.
2006 $workDigits[] = 0;
2007 }
2008 } else {
2009 // Finally! Actual division!
2010 $workDigits[] = intval( $work / $destBase );
2011
2012 // Isn't it annoying that most programming languages
2013 // don't have a single divide-and-remainder operator,
2014 // even though the CPU implements it that way?
2015 $work = $work % $destBase;
2016 }
2017 }
2018
2019 // All that division leaves us with a remainder,
2020 // which is conveniently our next output digit.
2021 $outChars .= $digitChars[$work];
2022
2023 // And we continue!
2024 $inDigits = $workDigits;
2025 }
2026
2027 while( strlen( $outChars ) < $pad ) {
2028 $outChars .= '0';
2029 }
2030
2031 return strrev( $outChars );
2032 }
2033
2034 /**
2035 * Create an object with a given name and an array of construct parameters
2036 * @param string $name
2037 * @param array $p parameters
2038 */
2039 function wfCreateObject( $name, $p ){
2040 $p = array_values( $p );
2041 switch ( count( $p ) ) {
2042 case 0:
2043 return new $name;
2044 case 1:
2045 return new $name( $p[0] );
2046 case 2:
2047 return new $name( $p[0], $p[1] );
2048 case 3:
2049 return new $name( $p[0], $p[1], $p[2] );
2050 case 4:
2051 return new $name( $p[0], $p[1], $p[2], $p[3] );
2052 case 5:
2053 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2054 case 6:
2055 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2056 default:
2057 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2058 }
2059 }
2060
2061 /**
2062 * Aliases for modularized functions
2063 */
2064 function wfGetHTTP( $url, $timeout = 'default' ) {
2065 return Http::get( $url, $timeout );
2066 }
2067 function wfIsLocalURL( $url ) {
2068 return Http::isLocalURL( $url );
2069 }
2070
2071 /**
2072 * Initialise php session
2073 */
2074 function wfSetupSession() {
2075 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2076 if( $wgSessionsInMemcached ) {
2077 require_once( 'MemcachedSessions.php' );
2078 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2079 # If it's left on 'user' or another setting from another
2080 # application, it will end up failing. Try to recover.
2081 ini_set ( 'session.save_handler', 'files' );
2082 }
2083 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2084 session_cache_limiter( 'private, must-revalidate' );
2085 @session_start();
2086 }
2087
2088 /**
2089 * Get an object from the precompiled serialized directory
2090 *
2091 * @return mixed The variable on success, false on failure
2092 */
2093 function wfGetPrecompiledData( $name ) {
2094 global $IP;
2095
2096 $file = "$IP/serialized/$name";
2097 if ( file_exists( $file ) ) {
2098 $blob = file_get_contents( $file );
2099 if ( $blob ) {
2100 return unserialize( $blob );
2101 }
2102 }
2103 return false;
2104 }
2105
2106 function wfGetCaller( $level = 2 ) {
2107 $backtrace = wfDebugBacktrace();
2108 if ( isset( $backtrace[$level] ) ) {
2109 if ( isset( $backtrace[$level]['class'] ) ) {
2110 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2111 } else {
2112 $caller = $backtrace[$level]['function'];
2113 }
2114 } else {
2115 $caller = 'unknown';
2116 }
2117 return $caller;
2118 }
2119
2120 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2121 function wfGetAllCallers() {
2122 return implode('/', array_map(
2123 create_function('$frame','
2124 return isset( $frame["class"] )?
2125 $frame["class"]."::".$frame["function"]:
2126 $frame["function"];
2127 '),
2128 array_reverse(wfDebugBacktrace())));
2129 }
2130
2131 /**
2132 * Get a cache key
2133 */
2134 function wfMemcKey( /*... */ ) {
2135 global $wgDBprefix, $wgDBname;
2136 $args = func_get_args();
2137 if ( $wgDBprefix ) {
2138 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2139 } else {
2140 $key = $wgDBname . ':' . implode( ':', $args );
2141 }
2142 return $key;
2143 }
2144
2145 /**
2146 * Get a cache key for a foreign DB
2147 */
2148 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2149 $args = array_slice( func_get_args(), 2 );
2150 if ( $prefix ) {
2151 $key = "$db-$prefix:" . implode( ':', $args );
2152 } else {
2153 $key = $db . ':' . implode( ':', $args );
2154 }
2155 return $key;
2156 }
2157
2158 /**
2159 * Get an ASCII string identifying this wiki
2160 * This is used as a prefix in memcached keys
2161 */
2162 function wfWikiID() {
2163 global $wgDBprefix, $wgDBname;
2164 if ( $wgDBprefix ) {
2165 return "$wgDBname-$wgDBprefix";
2166 } else {
2167 return $wgDBname;
2168 }
2169 }
2170
2171 /*
2172 * Get a Database object
2173 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2174 * master (for write queries), DB_SLAVE for potentially lagged
2175 * read queries, or an integer >= 0 for a particular server.
2176 *
2177 * @param mixed $groups Query groups. An array of group names that this query
2178 * belongs to. May contain a single string if the query is only
2179 * in one group.
2180 */
2181 function &wfGetDB( $db = DB_LAST, $groups = array() ) {
2182 global $wgLoadBalancer;
2183 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2184 return $ret;
2185 }
2186 ?>