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