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