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