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