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