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