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