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