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