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