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