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