Revert 'oops'
[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 $wgMemc;
1649 $key = wfMemcKey( 'stats', $key );
1650 if ( is_null( $wgMemc->incr( $key ) ) ) {
1651 $wgMemc->add( $key, 1 );
1652 }
1653 }
1654
1655 /**
1656 * @param mixed $nr The number to format
1657 * @param int $acc The number of digits after the decimal point, default 2
1658 * @param bool $round Whether or not to round the value, default true
1659 * @return float
1660 */
1661 function wfPercent( $nr, $acc = 2, $round = true ) {
1662 $ret = sprintf( "%.${acc}f", $nr );
1663 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1664 }
1665
1666 /**
1667 * Encrypt a username/password.
1668 *
1669 * @param string $userid ID of the user
1670 * @param string $password Password of the user
1671 * @return string Hashed password
1672 */
1673 function wfEncryptPassword( $userid, $password ) {
1674 global $wgPasswordSalt;
1675 $p = md5( $password);
1676
1677 if($wgPasswordSalt)
1678 return md5( "{$userid}-{$p}" );
1679 else
1680 return $p;
1681 }
1682
1683 /**
1684 * Appends to second array if $value differs from that in $default
1685 */
1686 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1687 if ( is_null( $changed ) ) {
1688 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1689 }
1690 if ( $default[$key] !== $value ) {
1691 $changed[$key] = $value;
1692 }
1693 }
1694
1695 /**
1696 * Since wfMsg() and co suck, they don't return false if the message key they
1697 * looked up didn't exist but a XHTML string, this function checks for the
1698 * nonexistance of messages by looking at wfMsg() output
1699 *
1700 * @param $msg The message key looked up
1701 * @param $wfMsgOut The output of wfMsg*()
1702 * @return bool
1703 */
1704 function wfEmptyMsg( $msg, $wfMsgOut ) {
1705 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1706 }
1707
1708 /**
1709 * Find out whether or not a mixed variable exists in a string
1710 *
1711 * @param mixed needle
1712 * @param string haystack
1713 * @return bool
1714 */
1715 function in_string( $needle, $str ) {
1716 return strpos( $str, $needle ) !== false;
1717 }
1718
1719 function wfSpecialList( $page, $details ) {
1720 global $wgContLang;
1721 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1722 return $page . $details;
1723 }
1724
1725 /**
1726 * Returns a regular expression of url protocols
1727 *
1728 * @return string
1729 */
1730 function wfUrlProtocols() {
1731 global $wgUrlProtocols;
1732
1733 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1734 // with LocalSettings files from 1.5
1735 if ( is_array( $wgUrlProtocols ) ) {
1736 $protocols = array();
1737 foreach ($wgUrlProtocols as $protocol)
1738 $protocols[] = preg_quote( $protocol, '/' );
1739
1740 return implode( '|', $protocols );
1741 } else {
1742 return $wgUrlProtocols;
1743 }
1744 }
1745
1746 /**
1747 * Safety wrapper around ini_get() for boolean settings.
1748 * The values returned from ini_get() are pre-normalized for settings
1749 * set via php.ini or php_flag/php_admin_flag... but *not*
1750 * for those set via php_value/php_admin_value.
1751 *
1752 * It's fairly common for people to use php_value instead of php_flag,
1753 * which can leave you with an 'off' setting giving a false positive
1754 * for code that just takes the ini_get() return value as a boolean.
1755 *
1756 * To make things extra interesting, setting via php_value accepts
1757 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1758 * Unrecognized values go false... again opposite PHP's own coercion
1759 * from string to bool.
1760 *
1761 * Luckily, 'properly' set settings will always come back as '0' or '1',
1762 * so we only have to worry about them and the 'improper' settings.
1763 *
1764 * I frickin' hate PHP... :P
1765 *
1766 * @param string $setting
1767 * @return bool
1768 */
1769 function wfIniGetBool( $setting ) {
1770 $val = ini_get( $setting );
1771 // 'on' and 'true' can't have whitespace around them, but '1' can.
1772 return strtolower( $val ) == 'on'
1773 || strtolower( $val ) == 'true'
1774 || strtolower( $val ) == 'yes'
1775 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1776 }
1777
1778 /**
1779 * Execute a shell command, with time and memory limits mirrored from the PHP
1780 * configuration if supported.
1781 * @param $cmd Command line, properly escaped for shell.
1782 * @param &$retval optional, will receive the program's exit code.
1783 * (non-zero is usually failure)
1784 * @return collected stdout as a string (trailing newlines stripped)
1785 */
1786 function wfShellExec( $cmd, &$retval=null ) {
1787 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1788
1789 if( wfIniGetBool( 'safe_mode' ) ) {
1790 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1791 $retval = 1;
1792 return "Unable to run external programs in safe mode.";
1793 }
1794
1795 if ( php_uname( 's' ) == 'Linux' ) {
1796 $time = intval( ini_get( 'max_execution_time' ) );
1797 $mem = intval( $wgMaxShellMemory );
1798 $filesize = intval( $wgMaxShellFileSize );
1799
1800 if ( $time > 0 && $mem > 0 ) {
1801 $script = "$IP/bin/ulimit4.sh";
1802 if ( is_executable( $script ) ) {
1803 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1804 }
1805 }
1806 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1807 # This is a hack to work around PHP's flawed invocation of cmd.exe
1808 # http://news.php.net/php.internals/21796
1809 $cmd = '"' . $cmd . '"';
1810 }
1811 wfDebug( "wfShellExec: $cmd\n" );
1812
1813 $output = array();
1814 $retval = 1; // error by default?
1815 exec( $cmd, $output, $retval ); // returns the last line of output.
1816 return implode( "\n", $output );
1817
1818 }
1819
1820 /**
1821 * This function works like "use VERSION" in Perl, the program will die with a
1822 * backtrace if the current version of PHP is less than the version provided
1823 *
1824 * This is useful for extensions which due to their nature are not kept in sync
1825 * with releases, and might depend on other versions of PHP than the main code
1826 *
1827 * Note: PHP might die due to parsing errors in some cases before it ever
1828 * manages to call this function, such is life
1829 *
1830 * @see perldoc -f use
1831 *
1832 * @param mixed $version The version to check, can be a string, an integer, or
1833 * a float
1834 */
1835 function wfUsePHP( $req_ver ) {
1836 $php_ver = PHP_VERSION;
1837
1838 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1839 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1840 }
1841
1842 /**
1843 * This function works like "use VERSION" in Perl except it checks the version
1844 * of MediaWiki, the program will die with a backtrace if the current version
1845 * of MediaWiki is less than the version provided.
1846 *
1847 * This is useful for extensions which due to their nature are not kept in sync
1848 * with releases
1849 *
1850 * @see perldoc -f use
1851 *
1852 * @param mixed $version The version to check, can be a string, an integer, or
1853 * a float
1854 */
1855 function wfUseMW( $req_ver ) {
1856 global $wgVersion;
1857
1858 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1859 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1860 }
1861
1862 /**
1863 * @deprecated use StringUtils::escapeRegexReplacement
1864 */
1865 function wfRegexReplacement( $string ) {
1866 return StringUtils::escapeRegexReplacement( $string );
1867 }
1868
1869 /**
1870 * Return the final portion of a pathname.
1871 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1872 * http://bugs.php.net/bug.php?id=33898
1873 *
1874 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1875 * We'll consider it so always, as we don't want \s in our Unix paths either.
1876 *
1877 * @param string $path
1878 * @param string $suffix to remove if present
1879 * @return string
1880 */
1881 function wfBaseName( $path, $suffix='' ) {
1882 $encSuffix = ($suffix == '')
1883 ? ''
1884 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1885 $matches = array();
1886 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1887 return $matches[1];
1888 } else {
1889 return '';
1890 }
1891 }
1892
1893 /**
1894 * Generate a relative path name to the given file.
1895 * May explode on non-matching case-insensitive paths,
1896 * funky symlinks, etc.
1897 *
1898 * @param string $path Absolute destination path including target filename
1899 * @param string $from Absolute source path, directory only
1900 * @return string
1901 */
1902 function wfRelativePath( $path, $from ) {
1903 // Normalize mixed input on Windows...
1904 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1905 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1906
1907 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1908 $against = explode( DIRECTORY_SEPARATOR, $from );
1909
1910 // Trim off common prefix
1911 while( count( $pieces ) && count( $against )
1912 && $pieces[0] == $against[0] ) {
1913 array_shift( $pieces );
1914 array_shift( $against );
1915 }
1916
1917 // relative dots to bump us to the parent
1918 while( count( $against ) ) {
1919 array_unshift( $pieces, '..' );
1920 array_shift( $against );
1921 }
1922
1923 array_push( $pieces, wfBaseName( $path ) );
1924
1925 return implode( DIRECTORY_SEPARATOR, $pieces );
1926 }
1927
1928 /**
1929 * Make a URL index, appropriate for the el_index field of externallinks.
1930 */
1931 function wfMakeUrlIndex( $url ) {
1932 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1933 $bits = parse_url( $url );
1934 wfSuppressWarnings();
1935 wfRestoreWarnings();
1936 if ( !$bits ) {
1937 return false;
1938 }
1939 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1940 $delimiter = '';
1941 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1942 $delimiter = '://';
1943 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1944 $delimiter = ':';
1945 // parse_url detects for news: and mailto: the host part of an url as path
1946 // We have to correct this wrong detection
1947 if ( isset ( $bits['path'] ) ) {
1948 $bits['host'] = $bits['path'];
1949 $bits['path'] = '';
1950 }
1951 } else {
1952 return false;
1953 }
1954
1955 // Reverse the labels in the hostname, convert to lower case
1956 // For emails reverse domainpart only
1957 if ( $bits['scheme'] == 'mailto' ) {
1958 $mailparts = explode( '@', $bits['host'], 2 );
1959 if ( count($mailparts) === 2 ) {
1960 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1961 } else {
1962 // No domain specified, don't mangle it
1963 $domainpart = '';
1964 }
1965 $reversedHost = $domainpart . '@' . $mailparts[0];
1966 } else {
1967 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1968 }
1969 // Add an extra dot to the end
1970 // Why? Is it in wrong place in mailto links?
1971 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1972 $reversedHost .= '.';
1973 }
1974 // Reconstruct the pseudo-URL
1975 $prot = $bits['scheme'];
1976 $index = "$prot$delimiter$reversedHost";
1977 // Leave out user and password. Add the port, path, query and fragment
1978 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1979 if ( isset( $bits['path'] ) ) {
1980 $index .= $bits['path'];
1981 } else {
1982 $index .= '/';
1983 }
1984 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1985 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1986 return $index;
1987 }
1988
1989 /**
1990 * Do any deferred updates and clear the list
1991 * TODO: This could be in Wiki.php if that class made any sense at all
1992 */
1993 function wfDoUpdates()
1994 {
1995 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1996 foreach ( $wgDeferredUpdateList as $update ) {
1997 $update->doUpdate();
1998 }
1999 foreach ( $wgPostCommitUpdateList as $update ) {
2000 $update->doUpdate();
2001 }
2002 $wgDeferredUpdateList = array();
2003 $wgPostCommitUpdateList = array();
2004 }
2005
2006 /**
2007 * @deprecated use StringUtils::explodeMarkup
2008 */
2009 function wfExplodeMarkup( $separator, $text ) {
2010 return StringUtils::explodeMarkup( $separator, $text );
2011 }
2012
2013 /**
2014 * Convert an arbitrarily-long digit string from one numeric base
2015 * to another, optionally zero-padding to a minimum column width.
2016 *
2017 * Supports base 2 through 36; digit values 10-36 are represented
2018 * as lowercase letters a-z. Input is case-insensitive.
2019 *
2020 * @param $input string of digits
2021 * @param $sourceBase int 2-36
2022 * @param $destBase int 2-36
2023 * @param $pad int 1 or greater
2024 * @param $lowercase bool
2025 * @return string or false on invalid input
2026 */
2027 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2028 $input = strval( $input );
2029 if( $sourceBase < 2 ||
2030 $sourceBase > 36 ||
2031 $destBase < 2 ||
2032 $destBase > 36 ||
2033 $pad < 1 ||
2034 $sourceBase != intval( $sourceBase ) ||
2035 $destBase != intval( $destBase ) ||
2036 $pad != intval( $pad ) ||
2037 !is_string( $input ) ||
2038 $input == '' ) {
2039 return false;
2040 }
2041 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2042 $inDigits = array();
2043 $outChars = '';
2044
2045 // Decode and validate input string
2046 $input = strtolower( $input );
2047 for( $i = 0; $i < strlen( $input ); $i++ ) {
2048 $n = strpos( $digitChars, $input{$i} );
2049 if( $n === false || $n > $sourceBase ) {
2050 return false;
2051 }
2052 $inDigits[] = $n;
2053 }
2054
2055 // Iterate over the input, modulo-ing out an output digit
2056 // at a time until input is gone.
2057 while( count( $inDigits ) ) {
2058 $work = 0;
2059 $workDigits = array();
2060
2061 // Long division...
2062 foreach( $inDigits as $digit ) {
2063 $work *= $sourceBase;
2064 $work += $digit;
2065
2066 if( $work < $destBase ) {
2067 // Gonna need to pull another digit.
2068 if( count( $workDigits ) ) {
2069 // Avoid zero-padding; this lets us find
2070 // the end of the input very easily when
2071 // length drops to zero.
2072 $workDigits[] = 0;
2073 }
2074 } else {
2075 // Finally! Actual division!
2076 $workDigits[] = intval( $work / $destBase );
2077
2078 // Isn't it annoying that most programming languages
2079 // don't have a single divide-and-remainder operator,
2080 // even though the CPU implements it that way?
2081 $work = $work % $destBase;
2082 }
2083 }
2084
2085 // All that division leaves us with a remainder,
2086 // which is conveniently our next output digit.
2087 $outChars .= $digitChars[$work];
2088
2089 // And we continue!
2090 $inDigits = $workDigits;
2091 }
2092
2093 while( strlen( $outChars ) < $pad ) {
2094 $outChars .= '0';
2095 }
2096
2097 return strrev( $outChars );
2098 }
2099
2100 /**
2101 * Create an object with a given name and an array of construct parameters
2102 * @param string $name
2103 * @param array $p parameters
2104 */
2105 function wfCreateObject( $name, $p ){
2106 $p = array_values( $p );
2107 switch ( count( $p ) ) {
2108 case 0:
2109 return new $name;
2110 case 1:
2111 return new $name( $p[0] );
2112 case 2:
2113 return new $name( $p[0], $p[1] );
2114 case 3:
2115 return new $name( $p[0], $p[1], $p[2] );
2116 case 4:
2117 return new $name( $p[0], $p[1], $p[2], $p[3] );
2118 case 5:
2119 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2120 case 6:
2121 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2122 default:
2123 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2124 }
2125 }
2126
2127 /**
2128 * Aliases for modularized functions
2129 */
2130 function wfGetHTTP( $url, $timeout = 'default' ) {
2131 return Http::get( $url, $timeout );
2132 }
2133 function wfIsLocalURL( $url ) {
2134 return Http::isLocalURL( $url );
2135 }
2136
2137 /**
2138 * Initialise php session
2139 */
2140 function wfSetupSession() {
2141 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2142 if( $wgSessionsInMemcached ) {
2143 require_once( 'MemcachedSessions.php' );
2144 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2145 # If it's left on 'user' or another setting from another
2146 # application, it will end up failing. Try to recover.
2147 ini_set ( 'session.save_handler', 'files' );
2148 }
2149 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2150 session_cache_limiter( 'private, must-revalidate' );
2151 @session_start();
2152 }
2153
2154 /**
2155 * Get an object from the precompiled serialized directory
2156 *
2157 * @return mixed The variable on success, false on failure
2158 */
2159 function wfGetPrecompiledData( $name ) {
2160 global $IP;
2161
2162 $file = "$IP/serialized/$name";
2163 if ( file_exists( $file ) ) {
2164 $blob = file_get_contents( $file );
2165 if ( $blob ) {
2166 return unserialize( $blob );
2167 }
2168 }
2169 return false;
2170 }
2171
2172 function wfGetCaller( $level = 2 ) {
2173 $backtrace = wfDebugBacktrace();
2174 if ( isset( $backtrace[$level] ) ) {
2175 return wfFormatStackFrame($backtrace[$level]);
2176 } else {
2177 $caller = 'unknown';
2178 }
2179 return $caller;
2180 }
2181
2182 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2183 function wfGetAllCallers() {
2184 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2185 }
2186
2187 /** Return a string representation of frame */
2188 function wfFormatStackFrame($frame) {
2189 return isset( $frame["class"] )?
2190 $frame["class"]."::".$frame["function"]:
2191 $frame["function"];
2192 }
2193
2194 /**
2195 * Get a cache key
2196 */
2197 function wfMemcKey( /*... */ ) {
2198 global $wgDBprefix, $wgDBname;
2199 $args = func_get_args();
2200 if ( $wgDBprefix ) {
2201 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2202 } else {
2203 $key = $wgDBname . ':' . implode( ':', $args );
2204 }
2205 return $key;
2206 }
2207
2208 /**
2209 * Get a cache key for a foreign DB
2210 */
2211 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2212 $args = array_slice( func_get_args(), 2 );
2213 if ( $prefix ) {
2214 $key = "$db-$prefix:" . implode( ':', $args );
2215 } else {
2216 $key = $db . ':' . implode( ':', $args );
2217 }
2218 return $key;
2219 }
2220
2221 /**
2222 * Get an ASCII string identifying this wiki
2223 * This is used as a prefix in memcached keys
2224 */
2225 function wfWikiID() {
2226 global $wgDBprefix, $wgDBname;
2227 if ( $wgDBprefix ) {
2228 return "$wgDBname-$wgDBprefix";
2229 } else {
2230 return $wgDBname;
2231 }
2232 }
2233
2234 /*
2235 * Get a Database object
2236 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2237 * master (for write queries), DB_SLAVE for potentially lagged
2238 * read queries, or an integer >= 0 for a particular server.
2239 *
2240 * @param mixed $groups Query groups. An array of group names that this query
2241 * belongs to. May contain a single string if the query is only
2242 * in one group.
2243 */
2244 function &wfGetDB( $db = DB_LAST, $groups = array() ) {
2245 global $wgLoadBalancer;
2246 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2247 return $ret;
2248 }
2249
2250 /**
2251 * Find a file.
2252 * Shortcut for RepoGroup::singleton()->findFile()
2253 * @param mixed $title Title object or string. May be interwiki.
2254 * @param mixed $time Requested time for an archived image, or false for the
2255 * current version. An image object will be returned which
2256 * existed at or before the specified time.
2257 * @return File, or false if the file does not exist
2258 */
2259 function wfFindFile( $title, $time = false ) {
2260 return RepoGroup::singleton()->findFile( $title, $time );
2261 }
2262
2263 /**
2264 * Get an object referring to a locally registered file.
2265 * Returns a valid placeholder object if the file does not exist.
2266 */
2267 function wfLocalFile( $title ) {
2268 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2269 }
2270
2271 /**
2272 * Should low-performance queries be disabled?
2273 *
2274 * @return bool
2275 */
2276 function wfQueriesMustScale() {
2277 global $wgMiserMode;
2278 return $wgMiserMode
2279 || ( SiteStats::pages() > 100000
2280 && SiteStats::edits() > 1000000
2281 && SiteStats::users() > 10000 );
2282 }
2283
2284 /**
2285 * Get the path to a specified script file, respecting file
2286 * extensions; this is a wrapper around $wgScriptExtension etc.
2287 *
2288 * @param string $script Script filename, sans extension
2289 * @return string
2290 */
2291 function wfScript( $script = 'index' ) {
2292 global $wgScriptPath, $wgScriptExtension;
2293 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2294 }
2295
2296 /**
2297 * Convenience function converts boolean values into "true"
2298 * or "false" (string) values
2299 *
2300 * @param bool $value
2301 * @return string
2302 */
2303 function wfBoolToStr( $value ) {
2304 return $value ? 'true' : 'false';
2305 }
2306
2307 /**
2308 * Load an extension messages file
2309 */
2310 function wfLoadExtensionMessages( $extensionName ) {
2311 global $wgExtensionMessagesFiles, $wgMessageCache;
2312 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2313 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2314 // Prevent double-loading
2315 $wgExtensionMessagesFiles[$extensionName] = false;
2316 }
2317 }
2318
2319 /**
2320 * Get a platform-independent path to the null file, e.g.
2321 * /dev/null
2322 *
2323 * @return string
2324 */
2325 function wfGetNull() {
2326 return wfIsWindows()
2327 ? 'NUL'
2328 : '/dev/null';
2329 }
2330
2331 /**
2332 * Displays a maxlag error
2333 *
2334 * @param string $host Server that lags the most
2335 * @param int $lag Maxlag (actual)
2336 * @param int $maxLag Maxlag (requested)
2337 */
2338 function wfMaxlagError( $host, $lag, $maxLag ) {
2339 global $wgShowHostnames;
2340 header( 'HTTP/1.1 503 Service Unavailable' );
2341 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2342 header( 'X-Database-Lag: ' . intval( $lag ) );
2343 header( 'Content-Type: text/plain' );
2344 if( $wgShowHostnames ) {
2345 echo "Waiting for $host: $lag seconds lagged\n";
2346 } else {
2347 echo "Waiting for a database server: $lag seconds lagged\n";
2348 }
2349 }