* Follow-up r84610: don't assume a Parser object is attached
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 /**
3 * Global functions used everywhere
4 * @file
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
9 }
10
11 require_once dirname( __FILE__ ) . '/normal/UtfNormalUtil.php';
12
13 // Hide compatibility functions from Doxygen
14 /// @cond
15
16 /**
17 * Compatibility functions
18 *
19 * We support PHP 5.1.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
22 */
23
24 if( !function_exists( 'iconv' ) ) {
25 /** @codeCoverageIgnore */
26 function iconv( $from, $to, $string ) {
27 return Fallback::iconv( $from, $to, $string );
28 }
29 }
30
31 if ( !function_exists( 'mb_substr' ) ) {
32 /** @codeCoverageIgnore */
33 function mb_substr( $str, $start, $count='end' ) {
34 return Fallback::mb_substr( $str, $start, $count );
35 }
36
37 /** @codeCoverageIgnore */
38 function mb_substr_split_unicode( $str, $splitPos ) {
39 return Fallback::mb_substr_split_unicode( $str, $splitPos );
40 }
41 }
42
43 if ( !function_exists( 'mb_strlen' ) ) {
44 /** @codeCoverageIgnore */
45 function mb_strlen( $str, $enc = '' ) {
46 return Fallback::mb_strlen( $str, $enc );
47 }
48 }
49
50 if( !function_exists( 'mb_strpos' ) ) {
51 /** @codeCoverageIgnore */
52 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
53 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
54 }
55
56 }
57
58 if( !function_exists( 'mb_strrpos' ) ) {
59 /** @codeCoverageIgnore */
60 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
61 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
62 }
63 }
64
65
66 // Support for Wietse Venema's taint feature
67 if ( !function_exists( 'istainted' ) ) {
68 /** @codeCoverageIgnore */
69 function istainted( $var ) {
70 return 0;
71 }
72 /** @codeCoverageIgnore */
73 function taint( $var, $level = 0 ) {}
74 /** @codeCoverageIgnore */
75 function untaint( $var, $level = 0 ) {}
76 define( 'TC_HTML', 1 );
77 define( 'TC_SHELL', 1 );
78 define( 'TC_MYSQL', 1 );
79 define( 'TC_PCRE', 1 );
80 define( 'TC_SELF', 1 );
81 }
82 /// @endcond
83
84 /**
85 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
86 */
87 function wfArrayDiff2( $a, $b ) {
88 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
89 }
90 function wfArrayDiff2_cmp( $a, $b ) {
91 if ( !is_array( $a ) ) {
92 return strcmp( $a, $b );
93 } elseif ( count( $a ) !== count( $b ) ) {
94 return count( $a ) < count( $b ) ? -1 : 1;
95 } else {
96 reset( $a );
97 reset( $b );
98 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
99 $cmp = strcmp( $valueA, $valueB );
100 if ( $cmp !== 0 ) {
101 return $cmp;
102 }
103 }
104 return 0;
105 }
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 some things to be included as literal characters in our title URLs
126 * for prettiness, which urlencode encodes by default. According to RFC 1738,
127 * all of the following should be safe:
128 *
129 * ;:@&=$-_.+!*'(),
130 *
131 * But + is not safe because it's used to indicate a space; &= are only safe in
132 * paths and not in queries (and we don't distinguish here); ' seems kind of
133 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
134 * is reserved, we don't care. So the list we unescape is:
135 *
136 * ;:@$!*(),/
137 *
138 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
139 * so no fancy : for IIS7.
140 *
141 * %2F in the page titles seems to fatally break for some reason.
142 *
143 * @param $s String:
144 * @return string
145 */
146 function wfUrlencode( $s ) {
147 static $needle;
148 if ( is_null( $needle ) ) {
149 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
150 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
151 $needle[] = '%3A';
152 }
153 }
154
155 $s = urlencode( $s );
156 $s = str_ireplace(
157 $needle,
158 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
159 $s
160 );
161
162 return $s;
163 }
164
165 /**
166 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
167 * In normal operation this is a NOP.
168 *
169 * Controlling globals:
170 * $wgDebugLogFile - points to the log file
171 * $wgProfileOnly - if set, normal debug messages will not be recorded.
172 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
173 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
174 *
175 * @param $text String
176 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
177 */
178 function wfDebug( $text, $logonly = false ) {
179 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
180 global $wgDebugLogPrefix, $wgShowDebug;
181
182 static $cache = array(); // Cache of unoutputted messages
183 $text = wfDebugTimer() . $text;
184
185 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
186 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
187 return;
188 }
189
190 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
191 $cache[] = $text;
192
193 if ( isset( $wgOut ) && StubObject::isRealObject( $wgOut ) ) {
194 // add the message and any cached messages to the output
195 array_map( array( $wgOut, 'debug' ), $cache );
196 $cache = array();
197 }
198 }
199 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
200 # Strip unprintables; they can switch terminal modes when binary data
201 # gets dumped, which is pretty annoying.
202 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
203 $text = $wgDebugLogPrefix . $text;
204 wfErrorLog( $text, $wgDebugLogFile );
205 }
206 }
207
208 function wfDebugTimer() {
209 global $wgDebugTimestamps;
210 if ( !$wgDebugTimestamps ) {
211 return '';
212 }
213 static $start = null;
214
215 if ( $start === null ) {
216 $start = microtime( true );
217 $prefix = "\n$start";
218 } else {
219 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
220 }
221
222 return $prefix . ' ';
223 }
224
225 /**
226 * Send a line giving PHP memory usage.
227 * @param $exact Bool: print exact values instead of kilobytes (default: false)
228 */
229 function wfDebugMem( $exact = false ) {
230 $mem = memory_get_usage();
231 if( !$exact ) {
232 $mem = floor( $mem / 1024 ) . ' kilobytes';
233 } else {
234 $mem .= ' bytes';
235 }
236 wfDebug( "Memory usage: $mem\n" );
237 }
238
239 /**
240 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
241 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
242 *
243 * @param $logGroup String
244 * @param $text String
245 * @param $public Bool: whether to log the event in the public log if no private
246 * log file is specified, (default true)
247 */
248 function wfDebugLog( $logGroup, $text, $public = true ) {
249 global $wgDebugLogGroups, $wgShowHostnames;
250 $text = trim( $text ) . "\n";
251 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
252 $time = wfTimestamp( TS_DB );
253 $wiki = wfWikiID();
254 if ( $wgShowHostnames ) {
255 $host = wfHostname();
256 } else {
257 $host = '';
258 }
259 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
260 } elseif ( $public === true ) {
261 wfDebug( $text, true );
262 }
263 }
264
265 /**
266 * Log for database errors
267 * @param $text String: database error message.
268 */
269 function wfLogDBError( $text ) {
270 global $wgDBerrorLog, $wgDBname;
271 if ( $wgDBerrorLog ) {
272 $host = trim(`hostname`);
273 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
274 wfErrorLog( $text, $wgDBerrorLog );
275 }
276 }
277
278 /**
279 * Log to a file without getting "file size exceeded" signals.
280 *
281 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
282 * send lines to the specified port, prefixed by the specified prefix and a space.
283 */
284 function wfErrorLog( $text, $file ) {
285 if ( substr( $file, 0, 4 ) == 'udp:' ) {
286 # Needs the sockets extension
287 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
288 // IPv6 bracketed host
289 $host = $m[2];
290 $port = intval( $m[3] );
291 $prefix = isset( $m[4] ) ? $m[4] : false;
292 $domain = AF_INET6;
293 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
294 $host = $m[2];
295 if ( !IP::isIPv4( $host ) ) {
296 $host = gethostbyname( $host );
297 }
298 $port = intval( $m[3] );
299 $prefix = isset( $m[4] ) ? $m[4] : false;
300 $domain = AF_INET;
301 } else {
302 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
303 }
304
305 // Clean it up for the multiplexer
306 if ( strval( $prefix ) !== '' ) {
307 $text = preg_replace( '/^/m', $prefix . ' ', $text );
308
309 // Limit to 64KB
310 if ( strlen( $text ) > 65534 ) {
311 $text = substr( $text, 0, 65534 );
312 }
313
314 if ( substr( $text, -1 ) != "\n" ) {
315 $text .= "\n";
316 }
317 } elseif ( strlen( $text ) > 65535 ) {
318 $text = substr( $text, 0, 65535 );
319 }
320
321 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
322 if ( !$sock ) {
323 return;
324 }
325 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
326 socket_close( $sock );
327 } else {
328 wfSuppressWarnings();
329 $exists = file_exists( $file );
330 $size = $exists ? filesize( $file ) : false;
331 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
332 error_log( $text, 3, $file );
333 }
334 wfRestoreWarnings();
335 }
336 }
337
338 /**
339 * @todo document
340 */
341 function wfLogProfilingData() {
342 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
343 global $wgProfiler, $wgProfileLimit, $wgUser;
344 # Profiling must actually be enabled...
345 if( is_null( $wgProfiler ) ) {
346 return;
347 }
348 # Get total page request time
349 $now = wfTime();
350 $elapsed = $now - $wgRequestTime;
351 # Only show pages that longer than $wgProfileLimit time (default is 0)
352 if( $elapsed <= $wgProfileLimit ) {
353 return;
354 }
355 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
356 $forward = '';
357 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
358 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
359 }
360 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
361 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
362 }
363 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
364 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
365 }
366 if( $forward ) {
367 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
368 }
369 // Don't unstub $wgUser at this late stage just for statistics purposes
370 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
371 if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
372 $forward .= ' anon';
373 }
374 $log = sprintf( "%s\t%04.3f\t%s\n",
375 gmdate( 'YmdHis' ), $elapsed,
376 urldecode( $wgRequest->getRequestURL() . $forward ) );
377 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
378 wfErrorLog( $log . $prof, $wgDebugLogFile );
379 }
380 }
381
382 /**
383 * Check if the wiki read-only lock file is present. This can be used to lock
384 * off editing functions, but doesn't guarantee that the database will not be
385 * modified.
386 * @return bool
387 */
388 function wfReadOnly() {
389 global $wgReadOnlyFile, $wgReadOnly;
390
391 if ( !is_null( $wgReadOnly ) ) {
392 return (bool)$wgReadOnly;
393 }
394 if ( $wgReadOnlyFile == '' ) {
395 return false;
396 }
397 // Set $wgReadOnly for faster access next time
398 if ( is_file( $wgReadOnlyFile ) ) {
399 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
400 } else {
401 $wgReadOnly = false;
402 }
403 return (bool)$wgReadOnly;
404 }
405
406 function wfReadOnlyReason() {
407 global $wgReadOnly;
408 wfReadOnly();
409 return $wgReadOnly;
410 }
411
412 /**
413 * Return a Language object from $langcode
414 * @param $langcode Mixed: either:
415 * - a Language object
416 * - code of the language to get the message for, if it is
417 * a valid code create a language for that language, if
418 * it is a string but not a valid code then make a basic
419 * language object
420 * - a boolean: if it's false then use the current users
421 * language (as a fallback for the old parameter
422 * functionality), or if it is true then use the wikis
423 * @return Language object
424 */
425 function wfGetLangObj( $langcode = false ) {
426 # Identify which language to get or create a language object for.
427 # Using is_object here due to Stub objects.
428 if( is_object( $langcode ) ) {
429 # Great, we already have the object (hopefully)!
430 return $langcode;
431 }
432
433 global $wgContLang, $wgLanguageCode;
434 if( $langcode === true || $langcode === $wgLanguageCode ) {
435 # $langcode is the language code of the wikis content language object.
436 # or it is a boolean and value is true
437 return $wgContLang;
438 }
439
440 global $wgLang;
441 if( $langcode === false || $langcode === $wgLang->getCode() ) {
442 # $langcode is the language code of user language object.
443 # or it was a boolean and value is false
444 return $wgLang;
445 }
446
447 $validCodes = array_keys( Language::getLanguageNames() );
448 if( in_array( $langcode, $validCodes ) ) {
449 # $langcode corresponds to a valid language.
450 return Language::factory( $langcode );
451 }
452
453 # $langcode is a string, but not a valid language code; use content language.
454 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
455 return $wgContLang;
456 }
457
458 /**
459 * Use this instead of $wgContLang, when working with user interface.
460 * User interface is currently hard coded according to wiki content language
461 * in many ways, especially regarding to text direction. There is lots stuff
462 * to fix, hence this function to keep the old behaviour unless the global
463 * $wgBetterDirectionality is enabled (or removed when everything works).
464 */
465 function wfUILang() {
466 global $wgBetterDirectionality;
467 return wfGetLangObj( !$wgBetterDirectionality );
468 }
469
470 /**
471 * This is the new function for getting translated interface messages.
472 * See the Message class for documentation how to use them.
473 * The intention is that this function replaces all old wfMsg* functions.
474 * @param $key \string Message key.
475 * Varargs: normal message parameters.
476 * @return Message
477 * @since 1.17
478 */
479 function wfMessage( $key /*...*/) {
480 $params = func_get_args();
481 array_shift( $params );
482 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
483 $params = $params[0];
484 }
485 return new Message( $key, $params );
486 }
487
488 /**
489 * This function accepts multiple message keys and returns a message instance
490 * for the first message which is non-empty. If all messages are empty then an
491 * instance of the first message key is returned.
492 * Varargs: message keys
493 * @return \type{Message}
494 * @since 1.18
495 */
496 function wfMessageFallback( /*...*/ ) {
497 $args = func_get_args();
498 return call_user_func_array( array( 'Message', 'newFallbackSequence' ), $args );
499 }
500
501 /**
502 * Get a message from anywhere, for the current user language.
503 *
504 * Use wfMsgForContent() instead if the message should NOT
505 * change depending on the user preferences.
506 *
507 * @param $key String: lookup key for the message, usually
508 * defined in languages/Language.php
509 *
510 * This function also takes extra optional parameters (not
511 * shown in the function definition), which can be used to
512 * insert variable text into the predefined message.
513 */
514 function wfMsg( $key ) {
515 $args = func_get_args();
516 array_shift( $args );
517 return wfMsgReal( $key, $args, true );
518 }
519
520 /**
521 * Same as above except doesn't transform the message
522 */
523 function wfMsgNoTrans( $key ) {
524 $args = func_get_args();
525 array_shift( $args );
526 return wfMsgReal( $key, $args, true, false, false );
527 }
528
529 /**
530 * Get a message from anywhere, for the current global language
531 * set with $wgLanguageCode.
532 *
533 * Use this if the message should NOT change dependent on the
534 * language set in the user's preferences. This is the case for
535 * most text written into logs, as well as link targets (such as
536 * the name of the copyright policy page). Link titles, on the
537 * other hand, should be shown in the UI language.
538 *
539 * Note that MediaWiki allows users to change the user interface
540 * language in their preferences, but a single installation
541 * typically only contains content in one language.
542 *
543 * Be wary of this distinction: If you use wfMsg() where you should
544 * use wfMsgForContent(), a user of the software may have to
545 * customize potentially hundreds of messages in
546 * order to, e.g., fix a link in every possible language.
547 *
548 * @param $key String: lookup key for the message, usually
549 * defined in languages/Language.php
550 */
551 function wfMsgForContent( $key ) {
552 global $wgForceUIMsgAsContentMsg;
553 $args = func_get_args();
554 array_shift( $args );
555 $forcontent = true;
556 if( is_array( $wgForceUIMsgAsContentMsg ) &&
557 in_array( $key, $wgForceUIMsgAsContentMsg ) )
558 {
559 $forcontent = false;
560 }
561 return wfMsgReal( $key, $args, true, $forcontent );
562 }
563
564 /**
565 * Same as above except doesn't transform the message
566 */
567 function wfMsgForContentNoTrans( $key ) {
568 global $wgForceUIMsgAsContentMsg;
569 $args = func_get_args();
570 array_shift( $args );
571 $forcontent = true;
572 if( is_array( $wgForceUIMsgAsContentMsg ) &&
573 in_array( $key, $wgForceUIMsgAsContentMsg ) )
574 {
575 $forcontent = false;
576 }
577 return wfMsgReal( $key, $args, true, $forcontent, false );
578 }
579
580 /**
581 * Get a message from the language file, for the UI elements
582 */
583 function wfMsgNoDB( $key ) {
584 $args = func_get_args();
585 array_shift( $args );
586 return wfMsgReal( $key, $args, false );
587 }
588
589 /**
590 * Get a message from the language file, for the content
591 */
592 function wfMsgNoDBForContent( $key ) {
593 global $wgForceUIMsgAsContentMsg;
594 $args = func_get_args();
595 array_shift( $args );
596 $forcontent = true;
597 if( is_array( $wgForceUIMsgAsContentMsg ) &&
598 in_array( $key, $wgForceUIMsgAsContentMsg ) )
599 {
600 $forcontent = false;
601 }
602 return wfMsgReal( $key, $args, false, $forcontent );
603 }
604
605
606 /**
607 * Really get a message
608 * @param $key String: key to get.
609 * @param $args
610 * @param $useDB Boolean
611 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
612 * @param $transform Boolean: Whether or not to transform the message.
613 * @return String: the requested message.
614 */
615 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
616 wfProfileIn( __METHOD__ );
617 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
618 $message = wfMsgReplaceArgs( $message, $args );
619 wfProfileOut( __METHOD__ );
620 return $message;
621 }
622
623 /**
624 * This function provides the message source for messages to be edited which are *not* stored in the database.
625 *
626 * @deprecated in 1.18; use wfMessage()
627 * @param $key String
628 */
629 function wfMsgWeirdKey( $key ) {
630 $source = wfMsgGetKey( $key, false, true, false );
631 if ( wfEmptyMsg( $key ) ) {
632 return '';
633 } else {
634 return $source;
635 }
636 }
637
638 /**
639 * Fetch a message string value, but don't replace any keys yet.
640 * @param $key String
641 * @param $useDB Bool
642 * @param $langCode String: Code of the language to get the message for, or
643 * behaves as a content language switch if it is a boolean.
644 * @param $transform Boolean: whether to parse magic words, etc.
645 * @return string
646 */
647 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
648 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
649
650 $cache = MessageCache::singleton();
651 $message = $cache->get( $key, $useDB, $langCode );
652 if( $message === false ) {
653 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
654 } elseif ( $transform ) {
655 $message = $cache->transform( $message );
656 }
657 return $message;
658 }
659
660 /**
661 * Replace message parameter keys on the given formatted output.
662 *
663 * @param $message String
664 * @param $args Array
665 * @return string
666 * @private
667 */
668 function wfMsgReplaceArgs( $message, $args ) {
669 # Fix windows line-endings
670 # Some messages are split with explode("\n", $msg)
671 $message = str_replace( "\r", '', $message );
672
673 // Replace arguments
674 if ( count( $args ) ) {
675 if ( is_array( $args[0] ) ) {
676 $args = array_values( $args[0] );
677 }
678 $replacementKeys = array();
679 foreach( $args as $n => $param ) {
680 $replacementKeys['$' . ( $n + 1 )] = $param;
681 }
682 $message = strtr( $message, $replacementKeys );
683 }
684
685 return $message;
686 }
687
688 /**
689 * Return an HTML-escaped version of a message.
690 * Parameter replacements, if any, are done *after* the HTML-escaping,
691 * so parameters may contain HTML (eg links or form controls). Be sure
692 * to pre-escape them if you really do want plaintext, or just wrap
693 * the whole thing in htmlspecialchars().
694 *
695 * @param $key String
696 * @param string ... parameters
697 * @return string
698 */
699 function wfMsgHtml( $key ) {
700 $args = func_get_args();
701 array_shift( $args );
702 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
703 }
704
705 /**
706 * Return an HTML version of message
707 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
708 * so parameters may contain HTML (eg links or form controls). Be sure
709 * to pre-escape them if you really do want plaintext, or just wrap
710 * the whole thing in htmlspecialchars().
711 *
712 * @param $key String
713 * @param string ... parameters
714 * @return string
715 */
716 function wfMsgWikiHtml( $key ) {
717 global $wgOut;
718 $args = func_get_args();
719 array_shift( $args );
720 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
721 }
722
723 /**
724 * Returns message in the requested format
725 * @param $key String: key of the message
726 * @param $options Array: processing rules. Can take the following options:
727 * <i>parse</i>: parses wikitext to HTML
728 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
729 * p's added by parser or tidy
730 * <i>escape</i>: filters message through htmlspecialchars
731 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
732 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
733 * <i>parsemag</i>: transform the message using magic phrases
734 * <i>content</i>: fetch message for content language instead of interface
735 * Also can accept a single associative argument, of the form 'language' => 'xx':
736 * <i>language</i>: Language object or language code to fetch message for
737 * (overriden by <i>content</i>), its behaviour with parse, parseinline
738 * and parsemag is undefined.
739 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
740 */
741 function wfMsgExt( $key, $options ) {
742 global $wgOut;
743
744 $args = func_get_args();
745 array_shift( $args );
746 array_shift( $args );
747 $options = (array)$options;
748
749 foreach( $options as $arrayKey => $option ) {
750 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
751 # An unknown index, neither numeric nor "language"
752 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
753 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
754 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
755 'replaceafter', 'parsemag', 'content' ) ) ) {
756 # A numeric index with unknown value
757 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
758 }
759 }
760
761 if( in_array( 'content', $options, true ) ) {
762 $forContent = true;
763 $langCode = true;
764 $langCodeObj = null;
765 } elseif( array_key_exists( 'language', $options ) ) {
766 $forContent = false;
767 $langCode = wfGetLangObj( $options['language'] );
768 $langCodeObj = $langCode;
769 } else {
770 $forContent = false;
771 $langCode = false;
772 $langCodeObj = null;
773 }
774
775 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
776
777 if( !in_array( 'replaceafter', $options, true ) ) {
778 $string = wfMsgReplaceArgs( $string, $args );
779 }
780
781 if( in_array( 'parse', $options, true ) ) {
782 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
783 } elseif ( in_array( 'parseinline', $options, true ) ) {
784 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
785 $m = array();
786 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
787 $string = $m[1];
788 }
789 } elseif ( in_array( 'parsemag', $options, true ) ) {
790 $string = MessageCache::singleton()->transform( $string,
791 !$forContent, $langCodeObj );
792 }
793
794 if ( in_array( 'escape', $options, true ) ) {
795 $string = htmlspecialchars ( $string );
796 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
797 $string = Sanitizer::escapeHtmlAllowEntities( $string );
798 }
799
800 if( in_array( 'replaceafter', $options, true ) ) {
801 $string = wfMsgReplaceArgs( $string, $args );
802 }
803
804 return $string;
805 }
806
807
808 /**
809 * Just like exit() but makes a note of it.
810 * Commits open transactions except if the error parameter is set
811 *
812 * @deprecated Please return control to the caller or throw an exception. Will
813 * be removed in 1.19.
814 */
815 function wfAbruptExit( $error = false ) {
816 static $called = false;
817 if ( $called ) {
818 exit( -1 );
819 }
820 $called = true;
821
822 wfDeprecated( __FUNCTION__ );
823 $bt = wfDebugBacktrace();
824 if( $bt ) {
825 for( $i = 0; $i < count( $bt ); $i++ ) {
826 $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
827 $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
828 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
829 }
830 } else {
831 wfDebug( "WARNING: Abrupt exit\n" );
832 }
833
834 wfLogProfilingData();
835
836 if ( !$error ) {
837 wfGetLB()->closeAll();
838 }
839 exit( -1 );
840 }
841
842 /**
843 * @deprecated Please return control the caller or throw an exception. Will
844 * be removed in 1.19.
845 */
846 function wfErrorExit() {
847 wfDeprecated( __FUNCTION__ );
848 wfAbruptExit( true );
849 }
850
851 /**
852 * Print a simple message and die, returning nonzero to the shell if any.
853 * Plain die() fails to return nonzero to the shell if you pass a string.
854 * @param $msg String
855 */
856 function wfDie( $msg = '' ) {
857 echo $msg;
858 die( 1 );
859 }
860
861 /**
862 * Throw a debugging exception. This function previously once exited the process,
863 * but now throws an exception instead, with similar results.
864 *
865 * @param $msg String: message shown when dieing.
866 */
867 function wfDebugDieBacktrace( $msg = '' ) {
868 throw new MWException( $msg );
869 }
870
871 /**
872 * Fetch server name for use in error reporting etc.
873 * Use real server name if available, so we know which machine
874 * in a server farm generated the current page.
875 * @return string
876 */
877 function wfHostname() {
878 static $host;
879 if ( is_null( $host ) ) {
880 if ( function_exists( 'posix_uname' ) ) {
881 // This function not present on Windows
882 $uname = @posix_uname();
883 } else {
884 $uname = false;
885 }
886 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
887 $host = $uname['nodename'];
888 } elseif ( getenv( 'COMPUTERNAME' ) ) {
889 # Windows computer name
890 $host = getenv( 'COMPUTERNAME' );
891 } else {
892 # This may be a virtual server.
893 $host = $_SERVER['SERVER_NAME'];
894 }
895 }
896 return $host;
897 }
898
899 /**
900 * Returns a HTML comment with the elapsed time since request.
901 * This method has no side effects.
902 * @return string
903 */
904 function wfReportTime() {
905 global $wgRequestTime, $wgShowHostnames;
906
907 $now = wfTime();
908 $elapsed = $now - $wgRequestTime;
909
910 return $wgShowHostnames
911 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
912 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
913 }
914
915 /**
916 * Safety wrapper for debug_backtrace().
917 *
918 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
919 * murky circumstances, which may be triggered in part by stub objects
920 * or other fancy talkin'.
921 *
922 * Will return an empty array if Zend Optimizer is detected or if
923 * debug_backtrace is disabled, otherwise the output from
924 * debug_backtrace() (trimmed).
925 *
926 * @return array of backtrace information
927 */
928 function wfDebugBacktrace() {
929 static $disabled = null;
930
931 if( extension_loaded( 'Zend Optimizer' ) ) {
932 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
933 return array();
934 }
935
936 if ( is_null( $disabled ) ) {
937 $disabled = false;
938 $functions = explode( ',', ini_get( 'disable_functions' ) );
939 $functions = array_map( 'trim', $functions );
940 $functions = array_map( 'strtolower', $functions );
941 if ( in_array( 'debug_backtrace', $functions ) ) {
942 wfDebug( "debug_backtrace is in disabled_functions\n" );
943 $disabled = true;
944 }
945 }
946 if ( $disabled ) {
947 return array();
948 }
949
950 return array_slice( debug_backtrace(), 1 );
951 }
952
953 function wfBacktrace() {
954 global $wgCommandLineMode;
955
956 if ( $wgCommandLineMode ) {
957 $msg = '';
958 } else {
959 $msg = "<ul>\n";
960 }
961 $backtrace = wfDebugBacktrace();
962 foreach( $backtrace as $call ) {
963 if( isset( $call['file'] ) ) {
964 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
965 $file = $f[count( $f ) - 1];
966 } else {
967 $file = '-';
968 }
969 if( isset( $call['line'] ) ) {
970 $line = $call['line'];
971 } else {
972 $line = '-';
973 }
974 if ( $wgCommandLineMode ) {
975 $msg .= "$file line $line calls ";
976 } else {
977 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
978 }
979 if( !empty( $call['class'] ) ) {
980 $msg .= $call['class'] . '::';
981 }
982 $msg .= $call['function'] . '()';
983
984 if ( $wgCommandLineMode ) {
985 $msg .= "\n";
986 } else {
987 $msg .= "</li>\n";
988 }
989 }
990 if ( $wgCommandLineMode ) {
991 $msg .= "\n";
992 } else {
993 $msg .= "</ul>\n";
994 }
995
996 return $msg;
997 }
998
999
1000 /* Some generic result counters, pulled out of SearchEngine */
1001
1002
1003 /**
1004 * @todo document
1005 */
1006 function wfShowingResults( $offset, $limit ) {
1007 global $wgLang;
1008 return wfMsgExt(
1009 'showingresults',
1010 array( 'parseinline' ),
1011 $wgLang->formatNum( $limit ),
1012 $wgLang->formatNum( $offset + 1 )
1013 );
1014 }
1015
1016 /**
1017 * @todo document
1018 */
1019 function wfShowingResultsNum( $offset, $limit, $num ) {
1020 global $wgLang;
1021 return wfMsgExt(
1022 'showingresultsnum',
1023 array( 'parseinline' ),
1024 $wgLang->formatNum( $limit ),
1025 $wgLang->formatNum( $offset + 1 ),
1026 $wgLang->formatNum( $num )
1027 );
1028 }
1029
1030 /**
1031 * Generate (prev x| next x) (20|50|100...) type links for paging
1032 * @param $offset String
1033 * @param $limit Integer
1034 * @param $link String
1035 * @param $query String: optional URL query parameter string
1036 * @param $atend Bool: optional param for specified if this is the last page
1037 */
1038 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1039 global $wgLang;
1040 $fmtLimit = $wgLang->formatNum( $limit );
1041 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1042 # Get prev/next link display text
1043 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1044 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1045 # Get prev/next link title text
1046 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1047 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1048 # Fetch the title object
1049 if( is_object( $link ) ) {
1050 $title =& $link;
1051 } else {
1052 $title = Title::newFromText( $link );
1053 if( is_null( $title ) ) {
1054 return false;
1055 }
1056 }
1057 # Make 'previous' link
1058 if( 0 != $offset ) {
1059 $po = $offset - $limit;
1060 $po = max( $po, 0 );
1061 $q = "limit={$limit}&offset={$po}";
1062 if( $query != '' ) {
1063 $q .= '&' . $query;
1064 }
1065 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1066 } else {
1067 $plink = $prev;
1068 }
1069 # Make 'next' link
1070 $no = $offset + $limit;
1071 $q = "limit={$limit}&offset={$no}";
1072 if( $query != '' ) {
1073 $q .= '&' . $query;
1074 }
1075 if( $atend ) {
1076 $nlink = $next;
1077 } else {
1078 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1079 }
1080 # Make links to set number of items per page
1081 $nums = $wgLang->pipeList( array(
1082 wfNumLink( $offset, 20, $title, $query ),
1083 wfNumLink( $offset, 50, $title, $query ),
1084 wfNumLink( $offset, 100, $title, $query ),
1085 wfNumLink( $offset, 250, $title, $query ),
1086 wfNumLink( $offset, 500, $title, $query )
1087 ) );
1088 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1089 }
1090
1091 /**
1092 * Generate links for (20|50|100...) items-per-page links
1093 * @param $offset String
1094 * @param $limit Integer
1095 * @param $title Title
1096 * @param $query String: optional URL query parameter string
1097 */
1098 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1099 global $wgLang;
1100 if( $query == '' ) {
1101 $q = '';
1102 } else {
1103 $q = $query.'&';
1104 }
1105 $q .= "limit={$limit}&offset={$offset}";
1106 $fmtLimit = $wgLang->formatNum( $limit );
1107 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1108 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1109 return $s;
1110 }
1111
1112 /**
1113 * @todo document
1114 * @todo FIXME: we may want to blacklist some broken browsers
1115 *
1116 * @return bool Whereas client accept gzip compression
1117 */
1118 function wfClientAcceptsGzip( $force = false ) {
1119 static $result = null;
1120 if ( $result === null || $force ) {
1121 $result = false;
1122 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1123 # FIXME: we may want to blacklist some broken browsers
1124 $m = array();
1125 if( preg_match(
1126 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1127 $_SERVER['HTTP_ACCEPT_ENCODING'],
1128 $m )
1129 )
1130 {
1131 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1132 $result = false;
1133 return $result;
1134 }
1135 wfDebug( " accepts gzip\n" );
1136 $result = true;
1137 }
1138 }
1139 }
1140 return $result;
1141 }
1142
1143 /**
1144 * Obtain the offset and limit values from the request string;
1145 * used in special pages
1146 *
1147 * @param $deflimit Default limit if none supplied
1148 * @param $optionname Name of a user preference to check against
1149 * @return array
1150 *
1151 */
1152 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1153 global $wgRequest;
1154 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1155 }
1156
1157 /**
1158 * Escapes the given text so that it may be output using addWikiText()
1159 * without any linking, formatting, etc. making its way through. This
1160 * is achieved by substituting certain characters with HTML entities.
1161 * As required by the callers, <nowiki> is not used.
1162 *
1163 * @param $text String: text to be escaped
1164 */
1165 function wfEscapeWikiText( $text ) {
1166 $text = strtr( "\n$text", array(
1167 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1168 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1169 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1170 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
1171 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
1172 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
1173 ) );
1174 return substr( $text, 1 );
1175 }
1176
1177 /**
1178 * @todo document
1179 * @return float
1180 */
1181 function wfTime() {
1182 return microtime( true );
1183 }
1184
1185 /**
1186 * Sets dest to source and returns the original value of dest
1187 * If source is NULL, it just returns the value, it doesn't set the variable
1188 * If force is true, it will set the value even if source is NULL
1189 */
1190 function wfSetVar( &$dest, $source, $force = false ) {
1191 $temp = $dest;
1192 if ( !is_null( $source ) || $force ) {
1193 $dest = $source;
1194 }
1195 return $temp;
1196 }
1197
1198 /**
1199 * As for wfSetVar except setting a bit
1200 */
1201 function wfSetBit( &$dest, $bit, $state = true ) {
1202 $temp = (bool)( $dest & $bit );
1203 if ( !is_null( $state ) ) {
1204 if ( $state ) {
1205 $dest |= $bit;
1206 } else {
1207 $dest &= ~$bit;
1208 }
1209 }
1210 return $temp;
1211 }
1212
1213 /**
1214 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1215 * "days=7&limit=100". Options in the first array override options in the second.
1216 * Options set to "" will not be output.
1217 */
1218 function wfArrayToCGI( $array1, $array2 = null ) {
1219 if ( !is_null( $array2 ) ) {
1220 $array1 = $array1 + $array2;
1221 }
1222
1223 $cgi = '';
1224 foreach ( $array1 as $key => $value ) {
1225 if ( $value !== '' ) {
1226 if ( $cgi != '' ) {
1227 $cgi .= '&';
1228 }
1229 if ( is_array( $value ) ) {
1230 $firstTime = true;
1231 foreach ( $value as $v ) {
1232 $cgi .= ( $firstTime ? '' : '&') .
1233 urlencode( $key . '[]' ) . '=' .
1234 urlencode( $v );
1235 $firstTime = false;
1236 }
1237 } else {
1238 if ( is_object( $value ) ) {
1239 $value = $value->__toString();
1240 }
1241 $cgi .= urlencode( $key ) . '=' .
1242 urlencode( $value );
1243 }
1244 }
1245 }
1246 return $cgi;
1247 }
1248
1249 /**
1250 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1251 * its argument and returns the same string in array form. This allows compa-
1252 * tibility with legacy functions that accept raw query strings instead of nice
1253 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1254 * valid query strings, or it will explode.
1255 *
1256 * @param $query String: query string
1257 * @return array Array version of input
1258 */
1259 function wfCgiToArray( $query ) {
1260 if( isset( $query[0] ) && $query[0] == '?' ) {
1261 $query = substr( $query, 1 );
1262 }
1263 $bits = explode( '&', $query );
1264 $ret = array();
1265 foreach( $bits as $bit ) {
1266 if( $bit === '' ) {
1267 continue;
1268 }
1269 list( $key, $value ) = explode( '=', $bit );
1270 $key = urldecode( $key );
1271 $value = urldecode( $value );
1272 $ret[$key] = $value;
1273 }
1274 return $ret;
1275 }
1276
1277 /**
1278 * Append a query string to an existing URL, which may or may not already
1279 * have query string parameters already. If so, they will be combined.
1280 *
1281 * @param $url String
1282 * @param $query Mixed: string or associative array
1283 * @return string
1284 */
1285 function wfAppendQuery( $url, $query ) {
1286 if ( is_array( $query ) ) {
1287 $query = wfArrayToCGI( $query );
1288 }
1289 if( $query != '' ) {
1290 if( false === strpos( $url, '?' ) ) {
1291 $url .= '?';
1292 } else {
1293 $url .= '&';
1294 }
1295 $url .= $query;
1296 }
1297 return $url;
1298 }
1299
1300 /**
1301 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1302 * and $wgProto are correct.
1303 *
1304 * @todo this won't work with current-path-relative URLs
1305 * like "subdir/foo.html", etc.
1306 *
1307 * @param $url String: either fully-qualified or a local path + query
1308 * @return string Fully-qualified URL
1309 */
1310 function wfExpandUrl( $url ) {
1311 if( substr( $url, 0, 2 ) == '//' ) {
1312 global $wgProto;
1313 return $wgProto . ':' . $url;
1314 } elseif( substr( $url, 0, 1 ) == '/' ) {
1315 global $wgServer;
1316 return $wgServer . $url;
1317 } else {
1318 return $url;
1319 }
1320 }
1321
1322 /**
1323 * Windows-compatible version of escapeshellarg()
1324 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1325 * function puts single quotes in regardless of OS.
1326 *
1327 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1328 * earlier distro releases of PHP)
1329 */
1330 function wfEscapeShellArg( ) {
1331 wfInitShellLocale();
1332
1333 $args = func_get_args();
1334 $first = true;
1335 $retVal = '';
1336 foreach ( $args as $arg ) {
1337 if ( !$first ) {
1338 $retVal .= ' ';
1339 } else {
1340 $first = false;
1341 }
1342
1343 if ( wfIsWindows() ) {
1344 // Escaping for an MSVC-style command line parser and CMD.EXE
1345 // Refs:
1346 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1347 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1348 // * Bug #13518
1349 // * CR r63214
1350 // Double the backslashes before any double quotes. Escape the double quotes.
1351 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1352 $arg = '';
1353 $iteration = 0;
1354 foreach ( $tokens as $token ) {
1355 if ( $iteration % 2 == 1 ) {
1356 // Delimiter, a double quote preceded by zero or more slashes
1357 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1358 } elseif ( $iteration % 4 == 2 ) {
1359 // ^ in $token will be outside quotes, need to be escaped
1360 $arg .= str_replace( '^', '^^', $token );
1361 } else { // $iteration % 4 == 0
1362 // ^ in $token will appear inside double quotes, so leave as is
1363 $arg .= $token;
1364 }
1365 $iteration++;
1366 }
1367 // Double the backslashes before the end of the string, because
1368 // we will soon add a quote
1369 $m = array();
1370 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1371 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1372 }
1373
1374 // Add surrounding quotes
1375 $retVal .= '"' . $arg . '"';
1376 } else {
1377 $retVal .= escapeshellarg( $arg );
1378 }
1379 }
1380 return $retVal;
1381 }
1382
1383 /**
1384 * wfMerge attempts to merge differences between three texts.
1385 * Returns true for a clean merge and false for failure or a conflict.
1386 */
1387 function wfMerge( $old, $mine, $yours, &$result ) {
1388 global $wgDiff3;
1389
1390 # This check may also protect against code injection in
1391 # case of broken installations.
1392 wfSuppressWarnings();
1393 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1394 wfRestoreWarnings();
1395
1396 if( !$haveDiff3 ) {
1397 wfDebug( "diff3 not found\n" );
1398 return false;
1399 }
1400
1401 # Make temporary files
1402 $td = wfTempDir();
1403 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1404 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1405 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1406
1407 fwrite( $oldtextFile, $old );
1408 fclose( $oldtextFile );
1409 fwrite( $mytextFile, $mine );
1410 fclose( $mytextFile );
1411 fwrite( $yourtextFile, $yours );
1412 fclose( $yourtextFile );
1413
1414 # Check for a conflict
1415 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1416 wfEscapeShellArg( $mytextName ) . ' ' .
1417 wfEscapeShellArg( $oldtextName ) . ' ' .
1418 wfEscapeShellArg( $yourtextName );
1419 $handle = popen( $cmd, 'r' );
1420
1421 if( fgets( $handle, 1024 ) ) {
1422 $conflict = true;
1423 } else {
1424 $conflict = false;
1425 }
1426 pclose( $handle );
1427
1428 # Merge differences
1429 $cmd = $wgDiff3 . ' -a -e --merge ' .
1430 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1431 $handle = popen( $cmd, 'r' );
1432 $result = '';
1433 do {
1434 $data = fread( $handle, 8192 );
1435 if ( strlen( $data ) == 0 ) {
1436 break;
1437 }
1438 $result .= $data;
1439 } while ( true );
1440 pclose( $handle );
1441 unlink( $mytextName );
1442 unlink( $oldtextName );
1443 unlink( $yourtextName );
1444
1445 if ( $result === '' && $old !== '' && !$conflict ) {
1446 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1447 $conflict = true;
1448 }
1449 return !$conflict;
1450 }
1451
1452 /**
1453 * Returns unified plain-text diff of two texts.
1454 * Useful for machine processing of diffs.
1455 * @param $before String: the text before the changes.
1456 * @param $after String: the text after the changes.
1457 * @param $params String: command-line options for the diff command.
1458 * @return String: unified diff of $before and $after
1459 */
1460 function wfDiff( $before, $after, $params = '-u' ) {
1461 if ( $before == $after ) {
1462 return '';
1463 }
1464
1465 global $wgDiff;
1466 wfSuppressWarnings();
1467 $haveDiff = $wgDiff && file_exists( $wgDiff );
1468 wfRestoreWarnings();
1469
1470 # This check may also protect against code injection in
1471 # case of broken installations.
1472 if( !$haveDiff ) {
1473 wfDebug( "diff executable not found\n" );
1474 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1475 $format = new UnifiedDiffFormatter();
1476 return $format->format( $diffs );
1477 }
1478
1479 # Make temporary files
1480 $td = wfTempDir();
1481 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1482 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1483
1484 fwrite( $oldtextFile, $before );
1485 fclose( $oldtextFile );
1486 fwrite( $newtextFile, $after );
1487 fclose( $newtextFile );
1488
1489 // Get the diff of the two files
1490 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1491
1492 $h = popen( $cmd, 'r' );
1493
1494 $diff = '';
1495
1496 do {
1497 $data = fread( $h, 8192 );
1498 if ( strlen( $data ) == 0 ) {
1499 break;
1500 }
1501 $diff .= $data;
1502 } while ( true );
1503
1504 // Clean up
1505 pclose( $h );
1506 unlink( $oldtextName );
1507 unlink( $newtextName );
1508
1509 // Kill the --- and +++ lines. They're not useful.
1510 $diff_lines = explode( "\n", $diff );
1511 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1512 unset( $diff_lines[0] );
1513 }
1514 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1515 unset( $diff_lines[1] );
1516 }
1517
1518 $diff = implode( "\n", $diff_lines );
1519
1520 return $diff;
1521 }
1522
1523 /**
1524 * A wrapper around the PHP function var_export().
1525 * Either print it or add it to the regular output ($wgOut).
1526 *
1527 * @param $var A PHP variable to dump.
1528 */
1529 function wfVarDump( $var ) {
1530 global $wgOut;
1531 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1532 if ( headers_sent() || !@is_object( $wgOut ) ) {
1533 print $s;
1534 } else {
1535 $wgOut->addHTML( $s );
1536 }
1537 }
1538
1539 /**
1540 * Provide a simple HTTP error.
1541 */
1542 function wfHttpError( $code, $label, $desc ) {
1543 global $wgOut;
1544 $wgOut->disable();
1545 header( "HTTP/1.0 $code $label" );
1546 header( "Status: $code $label" );
1547 $wgOut->sendCacheControl();
1548
1549 header( 'Content-type: text/html; charset=utf-8' );
1550 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1551 '<html><head><title>' .
1552 htmlspecialchars( $label ) .
1553 '</title></head><body><h1>' .
1554 htmlspecialchars( $label ) .
1555 '</h1><p>' .
1556 nl2br( htmlspecialchars( $desc ) ) .
1557 "</p></body></html>\n";
1558 }
1559
1560 /**
1561 * Clear away any user-level output buffers, discarding contents.
1562 *
1563 * Suitable for 'starting afresh', for instance when streaming
1564 * relatively large amounts of data without buffering, or wanting to
1565 * output image files without ob_gzhandler's compression.
1566 *
1567 * The optional $resetGzipEncoding parameter controls suppression of
1568 * the Content-Encoding header sent by ob_gzhandler; by default it
1569 * is left. See comments for wfClearOutputBuffers() for why it would
1570 * be used.
1571 *
1572 * Note that some PHP configuration options may add output buffer
1573 * layers which cannot be removed; these are left in place.
1574 *
1575 * @param $resetGzipEncoding Bool
1576 */
1577 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1578 if( $resetGzipEncoding ) {
1579 // Suppress Content-Encoding and Content-Length
1580 // headers from 1.10+s wfOutputHandler
1581 global $wgDisableOutputCompression;
1582 $wgDisableOutputCompression = true;
1583 }
1584 while( $status = ob_get_status() ) {
1585 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1586 // Probably from zlib.output_compression or other
1587 // PHP-internal setting which can't be removed.
1588 //
1589 // Give up, and hope the result doesn't break
1590 // output behavior.
1591 break;
1592 }
1593 if( !ob_end_clean() ) {
1594 // Could not remove output buffer handler; abort now
1595 // to avoid getting in some kind of infinite loop.
1596 break;
1597 }
1598 if( $resetGzipEncoding ) {
1599 if( $status['name'] == 'ob_gzhandler' ) {
1600 // Reset the 'Content-Encoding' field set by this handler
1601 // so we can start fresh.
1602 if ( function_exists( 'header_remove' ) ) {
1603 // Available since PHP 5.3.0
1604 header_remove( 'Content-Encoding' );
1605 } else {
1606 // We need to provide a valid content-coding. See bug 28069
1607 header( 'Content-Encoding: identity' );
1608 }
1609 break;
1610 }
1611 }
1612 }
1613 }
1614
1615 /**
1616 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1617 *
1618 * Clear away output buffers, but keep the Content-Encoding header
1619 * produced by ob_gzhandler, if any.
1620 *
1621 * This should be used for HTTP 304 responses, where you need to
1622 * preserve the Content-Encoding header of the real result, but
1623 * also need to suppress the output of ob_gzhandler to keep to spec
1624 * and avoid breaking Firefox in rare cases where the headers and
1625 * body are broken over two packets.
1626 */
1627 function wfClearOutputBuffers() {
1628 wfResetOutputBuffers( false );
1629 }
1630
1631 /**
1632 * Converts an Accept-* header into an array mapping string values to quality
1633 * factors
1634 */
1635 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1636 # No arg means accept anything (per HTTP spec)
1637 if( !$accept ) {
1638 return array( $def => 1.0 );
1639 }
1640
1641 $prefs = array();
1642
1643 $parts = explode( ',', $accept );
1644
1645 foreach( $parts as $part ) {
1646 # FIXME: doesn't deal with params like 'text/html; level=1'
1647 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1648 $match = array();
1649 if( !isset( $qpart ) ) {
1650 $prefs[$value] = 1.0;
1651 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1652 $prefs[$value] = floatval( $match[1] );
1653 }
1654 }
1655
1656 return $prefs;
1657 }
1658
1659 /**
1660 * Checks if a given MIME type matches any of the keys in the given
1661 * array. Basic wildcards are accepted in the array keys.
1662 *
1663 * Returns the matching MIME type (or wildcard) if a match, otherwise
1664 * NULL if no match.
1665 *
1666 * @param $type String
1667 * @param $avail Array
1668 * @return string
1669 * @private
1670 */
1671 function mimeTypeMatch( $type, $avail ) {
1672 if( array_key_exists( $type, $avail ) ) {
1673 return $type;
1674 } else {
1675 $parts = explode( '/', $type );
1676 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1677 return $parts[0] . '/*';
1678 } elseif( array_key_exists( '*/*', $avail ) ) {
1679 return '*/*';
1680 } else {
1681 return null;
1682 }
1683 }
1684 }
1685
1686 /**
1687 * Returns the 'best' match between a client's requested internet media types
1688 * and the server's list of available types. Each list should be an associative
1689 * array of type to preference (preference is a float between 0.0 and 1.0).
1690 * Wildcards in the types are acceptable.
1691 *
1692 * @param $cprefs Array: client's acceptable type list
1693 * @param $sprefs Array: server's offered types
1694 * @return string
1695 *
1696 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1697 * XXX: generalize to negotiate other stuff
1698 */
1699 function wfNegotiateType( $cprefs, $sprefs ) {
1700 $combine = array();
1701
1702 foreach( array_keys($sprefs) as $type ) {
1703 $parts = explode( '/', $type );
1704 if( $parts[1] != '*' ) {
1705 $ckey = mimeTypeMatch( $type, $cprefs );
1706 if( $ckey ) {
1707 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1708 }
1709 }
1710 }
1711
1712 foreach( array_keys( $cprefs ) as $type ) {
1713 $parts = explode( '/', $type );
1714 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1715 $skey = mimeTypeMatch( $type, $sprefs );
1716 if( $skey ) {
1717 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1718 }
1719 }
1720 }
1721
1722 $bestq = 0;
1723 $besttype = null;
1724
1725 foreach( array_keys( $combine ) as $type ) {
1726 if( $combine[$type] > $bestq ) {
1727 $besttype = $type;
1728 $bestq = $combine[$type];
1729 }
1730 }
1731
1732 return $besttype;
1733 }
1734
1735 /**
1736 * Array lookup
1737 * Returns an array where the values in the first array are replaced by the
1738 * values in the second array with the corresponding keys
1739 *
1740 * @return array
1741 */
1742 function wfArrayLookup( $a, $b ) {
1743 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1744 }
1745
1746 /**
1747 * Convenience function; returns MediaWiki timestamp for the present time.
1748 * @return string
1749 */
1750 function wfTimestampNow() {
1751 # return NOW
1752 return wfTimestamp( TS_MW, time() );
1753 }
1754
1755 /**
1756 * Reference-counted warning suppression
1757 */
1758 function wfSuppressWarnings( $end = false ) {
1759 static $suppressCount = 0;
1760 static $originalLevel = false;
1761
1762 if ( $end ) {
1763 if ( $suppressCount ) {
1764 --$suppressCount;
1765 if ( !$suppressCount ) {
1766 error_reporting( $originalLevel );
1767 }
1768 }
1769 } else {
1770 if ( !$suppressCount ) {
1771 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
1772 }
1773 ++$suppressCount;
1774 }
1775 }
1776
1777 /**
1778 * Restore error level to previous value
1779 */
1780 function wfRestoreWarnings() {
1781 wfSuppressWarnings( true );
1782 }
1783
1784 # Autodetect, convert and provide timestamps of various types
1785
1786 /**
1787 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1788 */
1789 define( 'TS_UNIX', 0 );
1790
1791 /**
1792 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1793 */
1794 define( 'TS_MW', 1 );
1795
1796 /**
1797 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1798 */
1799 define( 'TS_DB', 2 );
1800
1801 /**
1802 * RFC 2822 format, for E-mail and HTTP headers
1803 */
1804 define( 'TS_RFC2822', 3 );
1805
1806 /**
1807 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1808 *
1809 * This is used by Special:Export
1810 */
1811 define( 'TS_ISO_8601', 4 );
1812
1813 /**
1814 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1815 *
1816 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1817 * DateTime tag and page 36 for the DateTimeOriginal and
1818 * DateTimeDigitized tags.
1819 */
1820 define( 'TS_EXIF', 5 );
1821
1822 /**
1823 * Oracle format time.
1824 */
1825 define( 'TS_ORACLE', 6 );
1826
1827 /**
1828 * Postgres format time.
1829 */
1830 define( 'TS_POSTGRES', 7 );
1831
1832 /**
1833 * DB2 format time
1834 */
1835 define( 'TS_DB2', 8 );
1836
1837 /**
1838 * ISO 8601 basic format with no timezone: 19860209T200000Z
1839 *
1840 * This is used by ResourceLoader
1841 */
1842 define( 'TS_ISO_8601_BASIC', 9 );
1843
1844 /**
1845 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1846 * function will autodetect which format is supplied and act
1847 * accordingly.
1848 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1849 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1850 */
1851 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1852 $uts = 0;
1853 $da = array();
1854 $strtime = '';
1855
1856 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
1857 $uts = time();
1858 $strtime = "@$uts";
1859 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1860 # TS_DB
1861 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1862 # TS_EXIF
1863 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1864 # TS_MW
1865 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1866 # TS_UNIX
1867 $uts = $ts;
1868 $strtime = "@$ts"; // Undocumented?
1869 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1870 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1871 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1872 str_replace( '+00:00', 'UTC', $ts ) );
1873 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1874 # TS_ISO_8601
1875 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1876 #TS_ISO_8601_BASIC
1877 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1878 # TS_POSTGRES
1879 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1880 # TS_POSTGRES
1881 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1882 # TS_DB2
1883 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1884 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1885 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
1886 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1887 # The regex is a superset of rfc2822 for readability
1888 $strtime = strtok( $ts, ';' );
1889 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
1890 # TS_RFC850
1891 $strtime = $ts;
1892 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
1893 # asctime
1894 $strtime = $ts;
1895 } else {
1896 # Bogus value...
1897 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
1898
1899 return false;
1900 }
1901
1902
1903
1904 static $formats = array(
1905 TS_UNIX => 'U',
1906 TS_MW => 'YmdHis',
1907 TS_DB => 'Y-m-d H:i:s',
1908 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
1909 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
1910 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
1911 TS_RFC2822 => 'D, d M Y H:i:s',
1912 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
1913 TS_POSTGRES => 'Y-m-d H:i:s',
1914 TS_DB2 => 'Y-m-d H:i:s',
1915 );
1916
1917 if ( !isset( $formats[$outputtype] ) ) {
1918 throw new MWException( 'wfTimestamp() called with illegal output type.' );
1919 }
1920
1921 if ( function_exists( "date_create" ) ) {
1922 if ( count( $da ) ) {
1923 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
1924 (int)$da[1], (int)$da[2], (int)$da[3],
1925 (int)$da[4], (int)$da[5], (int)$da[6]);
1926
1927 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
1928 } elseif ( $strtime ) {
1929 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
1930 } else {
1931 return false;
1932 }
1933
1934 if ( !$d ) {
1935 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1936 return false;
1937 }
1938
1939 $output = $d->format( $formats[$outputtype] );
1940 } else {
1941 if ( count( $da ) ) {
1942 // Warning! gmmktime() acts oddly if the month or day is set to 0
1943 // We may want to handle that explicitly at some point
1944 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
1945 (int)$da[2], (int)$da[3], (int)$da[1] );
1946 } elseif ( $strtime ) {
1947 $uts = strtotime( $strtime );
1948 }
1949
1950 if ( $uts === false ) {
1951 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
1952 return false;
1953 }
1954
1955 if ( TS_UNIX == $outputtype ) {
1956 return $uts;
1957 }
1958 $output = gmdate( $formats[$outputtype], $uts );
1959 }
1960
1961 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
1962 $output .= ' GMT';
1963 }
1964
1965 return $output;
1966 }
1967
1968 /**
1969 * Return a formatted timestamp, or null if input is null.
1970 * For dealing with nullable timestamp columns in the database.
1971 * @param $outputtype Integer
1972 * @param $ts String
1973 * @return String
1974 */
1975 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1976 if( is_null( $ts ) ) {
1977 return null;
1978 } else {
1979 return wfTimestamp( $outputtype, $ts );
1980 }
1981 }
1982
1983 /**
1984 * Check if the operating system is Windows
1985 *
1986 * @return Bool: true if it's Windows, False otherwise.
1987 */
1988 function wfIsWindows() {
1989 static $isWindows = null;
1990 if ( $isWindows === null ) {
1991 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
1992 }
1993 return $isWindows;
1994 }
1995
1996 /**
1997 * Swap two variables
1998 */
1999 function swap( &$x, &$y ) {
2000 $z = $x;
2001 $x = $y;
2002 $y = $z;
2003 }
2004
2005 /**
2006 * BC wrapper for MimeMagic::singleton()
2007 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2008 */
2009 function &wfGetMimeMagic() {
2010 wfDeprecated( __FUNCTION__ );
2011 return MimeMagic::singleton();
2012 }
2013
2014 /**
2015 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2016 * TEMP environment variables are then checked in sequence, and if none are set
2017 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2018 * or C:\Windows\Temp for Windows and hope for the best.
2019 * It is common to call it with tempnam().
2020 *
2021 * NOTE: When possible, use instead the tmpfile() function to create
2022 * temporary files to avoid race conditions on file creation, etc.
2023 *
2024 * @return String
2025 */
2026 function wfTempDir() {
2027 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2028 $tmp = getenv( $var );
2029 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2030 return $tmp;
2031 }
2032 }
2033 if( function_exists( 'sys_get_temp_dir' ) ) {
2034 return sys_get_temp_dir();
2035 }
2036 # Usual defaults
2037 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2038 }
2039
2040 /**
2041 * Make directory, and make all parent directories if they don't exist
2042 *
2043 * @param $dir String: full path to directory to create
2044 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2045 * @param $caller String: optional caller param for debugging.
2046 * @return bool
2047 */
2048 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2049 global $wgDirectoryMode;
2050
2051 if ( !is_null( $caller ) ) {
2052 wfDebug( "$caller: called wfMkdirParents($dir)" );
2053 }
2054
2055 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2056 return true;
2057 }
2058
2059 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2060
2061 if ( is_null( $mode ) ) {
2062 $mode = $wgDirectoryMode;
2063 }
2064
2065 // Turn off the normal warning, we're doing our own below
2066 wfSuppressWarnings();
2067 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2068 wfRestoreWarnings();
2069
2070 if( !$ok ) {
2071 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2072 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2073 }
2074 return $ok;
2075 }
2076
2077 /**
2078 * Increment a statistics counter
2079 */
2080 function wfIncrStats( $key, $count = 1 ) {
2081 global $wgStatsMethod;
2082
2083 $count = intval( $count );
2084
2085 if( $wgStatsMethod == 'udp' ) {
2086 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2087 static $socket;
2088
2089 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
2090
2091 if ( !$socket ) {
2092 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2093 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2094 socket_sendto(
2095 $socket,
2096 $statline,
2097 strlen( $statline ),
2098 0,
2099 $wgUDPProfilerHost,
2100 $wgUDPProfilerPort
2101 );
2102 }
2103 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2104 wfSuppressWarnings();
2105 socket_sendto(
2106 $socket,
2107 $statline,
2108 strlen( $statline ),
2109 0,
2110 $wgUDPProfilerHost,
2111 $wgUDPProfilerPort
2112 );
2113 wfRestoreWarnings();
2114 } elseif( $wgStatsMethod == 'cache' ) {
2115 global $wgMemc;
2116 $key = wfMemcKey( 'stats', $key );
2117 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2118 $wgMemc->add( $key, $count );
2119 }
2120 } else {
2121 // Disabled
2122 }
2123 }
2124
2125 /**
2126 * @param $nr Mixed: the number to format
2127 * @param $acc Integer: the number of digits after the decimal point, default 2
2128 * @param $round Boolean: whether or not to round the value, default true
2129 * @return float
2130 */
2131 function wfPercent( $nr, $acc = 2, $round = true ) {
2132 $ret = sprintf( "%.${acc}f", $nr );
2133 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2134 }
2135
2136 /**
2137 * Encrypt a username/password.
2138 *
2139 * @param $userid Integer: ID of the user
2140 * @param $password String: password of the user
2141 * @return String: hashed password
2142 * @deprecated Use User::crypt() or User::oldCrypt() instead
2143 */
2144 function wfEncryptPassword( $userid, $password ) {
2145 wfDeprecated(__FUNCTION__);
2146 # Just wrap around User::oldCrypt()
2147 return User::oldCrypt( $password, $userid );
2148 }
2149
2150 /**
2151 * Appends to second array if $value differs from that in $default
2152 */
2153 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2154 if ( is_null( $changed ) ) {
2155 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2156 }
2157 if ( $default[$key] !== $value ) {
2158 $changed[$key] = $value;
2159 }
2160 }
2161
2162 /**
2163 * Since wfMsg() and co suck, they don't return false if the message key they
2164 * looked up didn't exist but a XHTML string, this function checks for the
2165 * nonexistance of messages by looking at wfMsg() output
2166 *
2167 * @param $key String: the message key looked up
2168 * @return Boolean True if the message *doesn't* exist.
2169 */
2170 function wfEmptyMsg( $key ) {
2171 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
2172 }
2173
2174 /**
2175 * Find out whether or not a mixed variable exists in a string
2176 *
2177 * @param $needle String
2178 * @param $str String
2179 * @param $insensitive Boolean
2180 * @return Boolean
2181 */
2182 function in_string( $needle, $str, $insensitive = false ) {
2183 $func = 'strpos';
2184 if( $insensitive ) $func = 'stripos';
2185
2186 return $func( $str, $needle ) !== false;
2187 }
2188
2189 function wfSpecialList( $page, $details ) {
2190 global $wgContLang;
2191 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2192 return $page . $details;
2193 }
2194
2195 /**
2196 * Returns a regular expression of url protocols
2197 *
2198 * @return String
2199 */
2200 function wfUrlProtocols() {
2201 global $wgUrlProtocols;
2202
2203 static $retval = null;
2204 if ( !is_null( $retval ) ) {
2205 return $retval;
2206 }
2207
2208 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2209 // with LocalSettings files from 1.5
2210 if ( is_array( $wgUrlProtocols ) ) {
2211 $protocols = array();
2212 foreach ( $wgUrlProtocols as $protocol ) {
2213 $protocols[] = preg_quote( $protocol, '/' );
2214 }
2215
2216 $retval = implode( '|', $protocols );
2217 } else {
2218 $retval = $wgUrlProtocols;
2219 }
2220 return $retval;
2221 }
2222
2223 /**
2224 * Safety wrapper around ini_get() for boolean settings.
2225 * The values returned from ini_get() are pre-normalized for settings
2226 * set via php.ini or php_flag/php_admin_flag... but *not*
2227 * for those set via php_value/php_admin_value.
2228 *
2229 * It's fairly common for people to use php_value instead of php_flag,
2230 * which can leave you with an 'off' setting giving a false positive
2231 * for code that just takes the ini_get() return value as a boolean.
2232 *
2233 * To make things extra interesting, setting via php_value accepts
2234 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2235 * Unrecognized values go false... again opposite PHP's own coercion
2236 * from string to bool.
2237 *
2238 * Luckily, 'properly' set settings will always come back as '0' or '1',
2239 * so we only have to worry about them and the 'improper' settings.
2240 *
2241 * I frickin' hate PHP... :P
2242 *
2243 * @param $setting String
2244 * @return Bool
2245 */
2246 function wfIniGetBool( $setting ) {
2247 $val = ini_get( $setting );
2248 // 'on' and 'true' can't have whitespace around them, but '1' can.
2249 return strtolower( $val ) == 'on'
2250 || strtolower( $val ) == 'true'
2251 || strtolower( $val ) == 'yes'
2252 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2253 }
2254
2255 /**
2256 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2257 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2258 *
2259 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2260 * should be omitted
2261 * @return Bool - Whether or not the extension is loaded
2262 */
2263 function wfDl( $extension ) {
2264 if( extension_loaded( $extension ) ) {
2265 return true;
2266 }
2267
2268 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2269 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2270
2271 if( $canDl ) {
2272 wfSuppressWarnings();
2273 dl( $extension . '.' . PHP_SHLIB_SUFFIX );
2274 wfRestoreWarnings();
2275 }
2276 return extension_loaded( $extension );
2277 }
2278
2279 /**
2280 * Execute a shell command, with time and memory limits mirrored from the PHP
2281 * configuration if supported.
2282 * @param $cmd String Command line, properly escaped for shell.
2283 * @param &$retval optional, will receive the program's exit code.
2284 * (non-zero is usually failure)
2285 * @param $environ Array optional environment variables which should be
2286 * added to the executed command environment.
2287 * @return collected stdout as a string (trailing newlines stripped)
2288 */
2289 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2290 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2291
2292 static $disabled;
2293 if ( is_null( $disabled ) ) {
2294 $disabled = false;
2295 if( wfIniGetBool( 'safe_mode' ) ) {
2296 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2297 $disabled = 'safemode';
2298 } else {
2299 $functions = explode( ',', ini_get( 'disable_functions' ) );
2300 $functions = array_map( 'trim', $functions );
2301 $functions = array_map( 'strtolower', $functions );
2302 if ( in_array( 'passthru', $functions ) ) {
2303 wfDebug( "passthru is in disabled_functions\n" );
2304 $disabled = 'passthru';
2305 }
2306 }
2307 }
2308 if ( $disabled ) {
2309 $retval = 1;
2310 return $disabled == 'safemode' ?
2311 'Unable to run external programs in safe mode.' :
2312 'Unable to run external programs, passthru() is disabled.';
2313 }
2314
2315 wfInitShellLocale();
2316
2317 $envcmd = '';
2318 foreach( $environ as $k => $v ) {
2319 if ( wfIsWindows() ) {
2320 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2321 * appear in the environment variable, so we must use carat escaping as documented in
2322 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2323 * Note however that the quote isn't listed there, but is needed, and the parentheses
2324 * are listed there but doesn't appear to need it.
2325 */
2326 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2327 } else {
2328 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2329 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2330 */
2331 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2332 }
2333 }
2334 $cmd = $envcmd . $cmd;
2335
2336 if ( wfIsWindows() ) {
2337 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2338 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2339 {
2340 # Hack to work around PHP's flawed invocation of cmd.exe
2341 # http://news.php.net/php.internals/21796
2342 # Windows 9x doesn't accept any kind of quotes
2343 $cmd = '"' . $cmd . '"';
2344 }
2345 } elseif ( php_uname( 's' ) == 'Linux' ) {
2346 $time = intval( $wgMaxShellTime );
2347 $mem = intval( $wgMaxShellMemory );
2348 $filesize = intval( $wgMaxShellFileSize );
2349
2350 if ( $time > 0 && $mem > 0 ) {
2351 $script = "$IP/bin/ulimit4.sh";
2352 if ( is_executable( $script ) ) {
2353 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2354 }
2355 }
2356 }
2357 wfDebug( "wfShellExec: $cmd\n" );
2358
2359 $retval = 1; // error by default?
2360 ob_start();
2361 passthru( $cmd, $retval );
2362 $output = ob_get_contents();
2363 ob_end_clean();
2364
2365 if ( $retval == 127 ) {
2366 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2367 }
2368 return $output;
2369 }
2370
2371 /**
2372 * Workaround for http://bugs.php.net/bug.php?id=45132
2373 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2374 */
2375 function wfInitShellLocale() {
2376 static $done = false;
2377 if ( $done ) {
2378 return;
2379 }
2380 $done = true;
2381 global $wgShellLocale;
2382 if ( !wfIniGetBool( 'safe_mode' ) ) {
2383 putenv( "LC_CTYPE=$wgShellLocale" );
2384 setlocale( LC_CTYPE, $wgShellLocale );
2385 }
2386 }
2387
2388 /**
2389 * This function works like "use VERSION" in Perl, the program will die with a
2390 * backtrace if the current version of PHP is less than the version provided
2391 *
2392 * This is useful for extensions which due to their nature are not kept in sync
2393 * with releases, and might depend on other versions of PHP than the main code
2394 *
2395 * Note: PHP might die due to parsing errors in some cases before it ever
2396 * manages to call this function, such is life
2397 *
2398 * @see perldoc -f use
2399 *
2400 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2401 * a float
2402 */
2403 function wfUsePHP( $req_ver ) {
2404 $php_ver = PHP_VERSION;
2405
2406 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2407 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2408 }
2409 }
2410
2411 /**
2412 * This function works like "use VERSION" in Perl except it checks the version
2413 * of MediaWiki, the program will die with a backtrace if the current version
2414 * of MediaWiki is less than the version provided.
2415 *
2416 * This is useful for extensions which due to their nature are not kept in sync
2417 * with releases
2418 *
2419 * @see perldoc -f use
2420 *
2421 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2422 * a float
2423 */
2424 function wfUseMW( $req_ver ) {
2425 global $wgVersion;
2426
2427 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2428 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2429 }
2430 }
2431
2432 /**
2433 * Return the final portion of a pathname.
2434 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2435 * http://bugs.php.net/bug.php?id=33898
2436 *
2437 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2438 * We'll consider it so always, as we don't want \s in our Unix paths either.
2439 *
2440 * @param $path String
2441 * @param $suffix String: to remove if present
2442 * @return String
2443 */
2444 function wfBaseName( $path, $suffix = '' ) {
2445 $encSuffix = ( $suffix == '' )
2446 ? ''
2447 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2448 $matches = array();
2449 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2450 return $matches[1];
2451 } else {
2452 return '';
2453 }
2454 }
2455
2456 /**
2457 * Generate a relative path name to the given file.
2458 * May explode on non-matching case-insensitive paths,
2459 * funky symlinks, etc.
2460 *
2461 * @param $path String: absolute destination path including target filename
2462 * @param $from String: Absolute source path, directory only
2463 * @return String
2464 */
2465 function wfRelativePath( $path, $from ) {
2466 // Normalize mixed input on Windows...
2467 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2468 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2469
2470 // Trim trailing slashes -- fix for drive root
2471 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2472 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2473
2474 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2475 $against = explode( DIRECTORY_SEPARATOR, $from );
2476
2477 if( $pieces[0] !== $against[0] ) {
2478 // Non-matching Windows drive letters?
2479 // Return a full path.
2480 return $path;
2481 }
2482
2483 // Trim off common prefix
2484 while( count( $pieces ) && count( $against )
2485 && $pieces[0] == $against[0] ) {
2486 array_shift( $pieces );
2487 array_shift( $against );
2488 }
2489
2490 // relative dots to bump us to the parent
2491 while( count( $against ) ) {
2492 array_unshift( $pieces, '..' );
2493 array_shift( $against );
2494 }
2495
2496 array_push( $pieces, wfBaseName( $path ) );
2497
2498 return implode( DIRECTORY_SEPARATOR, $pieces );
2499 }
2500
2501 /**
2502 * Backwards array plus for people who haven't bothered to read the PHP manual
2503 * XXX: will not darn your socks for you.
2504 *
2505 * @param $array1 Array
2506 * @param [$array2, [...]] Arrays
2507 * @return Array
2508 */
2509 function wfArrayMerge( $array1/* ... */ ) {
2510 $args = func_get_args();
2511 $args = array_reverse( $args, true );
2512 $out = array();
2513 foreach ( $args as $arg ) {
2514 $out += $arg;
2515 }
2516 return $out;
2517 }
2518
2519 /**
2520 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2521 * e.g.
2522 * wfMergeErrorArrays(
2523 * array( array( 'x' ) ),
2524 * array( array( 'x', '2' ) ),
2525 * array( array( 'x' ) ),
2526 * array( array( 'y') )
2527 * );
2528 * returns:
2529 * array(
2530 * array( 'x', '2' ),
2531 * array( 'x' ),
2532 * array( 'y' )
2533 * )
2534 */
2535 function wfMergeErrorArrays( /*...*/ ) {
2536 $args = func_get_args();
2537 $out = array();
2538 foreach ( $args as $errors ) {
2539 foreach ( $errors as $params ) {
2540 # FIXME: sometimes get nested arrays for $params,
2541 # which leads to E_NOTICEs
2542 $spec = implode( "\t", $params );
2543 $out[$spec] = $params;
2544 }
2545 }
2546 return array_values( $out );
2547 }
2548
2549 /**
2550 * parse_url() work-alike, but non-broken. Differences:
2551 *
2552 * 1) Does not raise warnings on bad URLs (just returns false)
2553 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2554 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2555 *
2556 * @param $url String: a URL to parse
2557 * @return Array: bits of the URL in an associative array, per PHP docs
2558 */
2559 function wfParseUrl( $url ) {
2560 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2561 wfSuppressWarnings();
2562 $bits = parse_url( $url );
2563 wfRestoreWarnings();
2564 if ( !$bits ) {
2565 return false;
2566 }
2567
2568 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2569 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2570 $bits['delimiter'] = '://';
2571 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2572 $bits['delimiter'] = ':';
2573 // parse_url detects for news: and mailto: the host part of an url as path
2574 // We have to correct this wrong detection
2575 if ( isset( $bits['path'] ) ) {
2576 $bits['host'] = $bits['path'];
2577 $bits['path'] = '';
2578 }
2579 } else {
2580 return false;
2581 }
2582
2583 return $bits;
2584 }
2585
2586 /**
2587 * Make a URL index, appropriate for the el_index field of externallinks.
2588 */
2589 function wfMakeUrlIndex( $url ) {
2590 $bits = wfParseUrl( $url );
2591
2592 // Reverse the labels in the hostname, convert to lower case
2593 // For emails reverse domainpart only
2594 if ( $bits['scheme'] == 'mailto' ) {
2595 $mailparts = explode( '@', $bits['host'], 2 );
2596 if ( count( $mailparts ) === 2 ) {
2597 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2598 } else {
2599 // No domain specified, don't mangle it
2600 $domainpart = '';
2601 }
2602 $reversedHost = $domainpart . '@' . $mailparts[0];
2603 } else {
2604 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2605 }
2606 // Add an extra dot to the end
2607 // Why? Is it in wrong place in mailto links?
2608 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2609 $reversedHost .= '.';
2610 }
2611 // Reconstruct the pseudo-URL
2612 $prot = $bits['scheme'];
2613 $index = $prot . $bits['delimiter'] . $reversedHost;
2614 // Leave out user and password. Add the port, path, query and fragment
2615 if ( isset( $bits['port'] ) ) {
2616 $index .= ':' . $bits['port'];
2617 }
2618 if ( isset( $bits['path'] ) ) {
2619 $index .= $bits['path'];
2620 } else {
2621 $index .= '/';
2622 }
2623 if ( isset( $bits['query'] ) ) {
2624 $index .= '?' . $bits['query'];
2625 }
2626 if ( isset( $bits['fragment'] ) ) {
2627 $index .= '#' . $bits['fragment'];
2628 }
2629 return $index;
2630 }
2631
2632 /**
2633 * Do any deferred updates and clear the list
2634 *
2635 * @param $commit String: set to 'commit' to commit after every update to
2636 * prevent lock contention
2637 */
2638 function wfDoUpdates( $commit = '' ) {
2639 global $wgDeferredUpdateList;
2640
2641 wfProfileIn( __METHOD__ );
2642
2643 // No need to get master connections in case of empty updates array
2644 if ( !count( $wgDeferredUpdateList ) ) {
2645 wfProfileOut( __METHOD__ );
2646 return;
2647 }
2648
2649 $doCommit = $commit == 'commit';
2650 if ( $doCommit ) {
2651 $dbw = wfGetDB( DB_MASTER );
2652 }
2653
2654 foreach ( $wgDeferredUpdateList as $update ) {
2655 $update->doUpdate();
2656
2657 if ( $doCommit && $dbw->trxLevel() ) {
2658 $dbw->commit();
2659 }
2660 }
2661
2662 $wgDeferredUpdateList = array();
2663 wfProfileOut( __METHOD__ );
2664 }
2665
2666 /**
2667 * Convert an arbitrarily-long digit string from one numeric base
2668 * to another, optionally zero-padding to a minimum column width.
2669 *
2670 * Supports base 2 through 36; digit values 10-36 are represented
2671 * as lowercase letters a-z. Input is case-insensitive.
2672 *
2673 * @param $input String: of digits
2674 * @param $sourceBase Integer: 2-36
2675 * @param $destBase Integer: 2-36
2676 * @param $pad Integer: 1 or greater
2677 * @param $lowercase Boolean
2678 * @return String or false on invalid input
2679 */
2680 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2681 $input = strval( $input );
2682 if( $sourceBase < 2 ||
2683 $sourceBase > 36 ||
2684 $destBase < 2 ||
2685 $destBase > 36 ||
2686 $pad < 1 ||
2687 $sourceBase != intval( $sourceBase ) ||
2688 $destBase != intval( $destBase ) ||
2689 $pad != intval( $pad ) ||
2690 !is_string( $input ) ||
2691 $input == '' ) {
2692 return false;
2693 }
2694 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2695 $inDigits = array();
2696 $outChars = '';
2697
2698 // Decode and validate input string
2699 $input = strtolower( $input );
2700 for( $i = 0; $i < strlen( $input ); $i++ ) {
2701 $n = strpos( $digitChars, $input{$i} );
2702 if( $n === false || $n > $sourceBase ) {
2703 return false;
2704 }
2705 $inDigits[] = $n;
2706 }
2707
2708 // Iterate over the input, modulo-ing out an output digit
2709 // at a time until input is gone.
2710 while( count( $inDigits ) ) {
2711 $work = 0;
2712 $workDigits = array();
2713
2714 // Long division...
2715 foreach( $inDigits as $digit ) {
2716 $work *= $sourceBase;
2717 $work += $digit;
2718
2719 if( $work < $destBase ) {
2720 // Gonna need to pull another digit.
2721 if( count( $workDigits ) ) {
2722 // Avoid zero-padding; this lets us find
2723 // the end of the input very easily when
2724 // length drops to zero.
2725 $workDigits[] = 0;
2726 }
2727 } else {
2728 // Finally! Actual division!
2729 $workDigits[] = intval( $work / $destBase );
2730
2731 // Isn't it annoying that most programming languages
2732 // don't have a single divide-and-remainder operator,
2733 // even though the CPU implements it that way?
2734 $work = $work % $destBase;
2735 }
2736 }
2737
2738 // All that division leaves us with a remainder,
2739 // which is conveniently our next output digit.
2740 $outChars .= $digitChars[$work];
2741
2742 // And we continue!
2743 $inDigits = $workDigits;
2744 }
2745
2746 while( strlen( $outChars ) < $pad ) {
2747 $outChars .= '0';
2748 }
2749
2750 return strrev( $outChars );
2751 }
2752
2753 /**
2754 * Create an object with a given name and an array of construct parameters
2755 * @param $name String
2756 * @param $p Array: parameters
2757 * @deprecated
2758 */
2759 function wfCreateObject( $name, $p ) {
2760 return MWFunction::newObj( $name, $p );
2761 }
2762
2763 function wfHttpOnlySafe() {
2764 global $wgHttpOnlyBlacklist;
2765
2766 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2767 foreach( $wgHttpOnlyBlacklist as $regex ) {
2768 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2769 return false;
2770 }
2771 }
2772 }
2773
2774 return true;
2775 }
2776
2777 /**
2778 * Initialise php session
2779 */
2780 function wfSetupSession( $sessionId = false ) {
2781 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2782 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2783 if( $wgSessionsInMemcached ) {
2784 require_once( 'MemcachedSessions.php' );
2785 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2786 # Only set this if $wgSessionHandler isn't null and session.save_handler
2787 # hasn't already been set to the desired value (that causes errors)
2788 ini_set( 'session.save_handler', $wgSessionHandler );
2789 }
2790 $httpOnlySafe = wfHttpOnlySafe();
2791 wfDebugLog( 'cookie',
2792 'session_set_cookie_params: "' . implode( '", "',
2793 array(
2794 0,
2795 $wgCookiePath,
2796 $wgCookieDomain,
2797 $wgCookieSecure,
2798 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2799 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2800 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2801 } else {
2802 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2803 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2804 }
2805 session_cache_limiter( 'private, must-revalidate' );
2806 if ( $sessionId ) {
2807 session_id( $sessionId );
2808 }
2809 wfSuppressWarnings();
2810 session_start();
2811 wfRestoreWarnings();
2812 }
2813
2814 /**
2815 * Get an object from the precompiled serialized directory
2816 *
2817 * @return Mixed: the variable on success, false on failure
2818 */
2819 function wfGetPrecompiledData( $name ) {
2820 global $IP;
2821
2822 $file = "$IP/serialized/$name";
2823 if ( file_exists( $file ) ) {
2824 $blob = file_get_contents( $file );
2825 if ( $blob ) {
2826 return unserialize( $blob );
2827 }
2828 }
2829 return false;
2830 }
2831
2832 function wfGetCaller( $level = 2 ) {
2833 $backtrace = wfDebugBacktrace();
2834 if ( isset( $backtrace[$level] ) ) {
2835 return wfFormatStackFrame( $backtrace[$level] );
2836 } else {
2837 $caller = 'unknown';
2838 }
2839 return $caller;
2840 }
2841
2842 /**
2843 * Return a string consisting of callers in the stack. Useful sometimes
2844 * for profiling specific points.
2845 *
2846 * @param $limit The maximum depth of the stack frame to return, or false for
2847 * the entire stack.
2848 */
2849 function wfGetAllCallers( $limit = 3 ) {
2850 $trace = array_reverse( wfDebugBacktrace() );
2851 if ( !$limit || $limit > count( $trace ) - 1 ) {
2852 $limit = count( $trace ) - 1;
2853 }
2854 $trace = array_slice( $trace, -$limit - 1, $limit );
2855 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2856 }
2857
2858 /**
2859 * Return a string representation of frame
2860 */
2861 function wfFormatStackFrame( $frame ) {
2862 return isset( $frame['class'] ) ?
2863 $frame['class'] . '::' . $frame['function'] :
2864 $frame['function'];
2865 }
2866
2867 /**
2868 * Get a cache key
2869 */
2870 function wfMemcKey( /*... */ ) {
2871 $args = func_get_args();
2872 $key = wfWikiID() . ':' . implode( ':', $args );
2873 $key = str_replace( ' ', '_', $key );
2874 return $key;
2875 }
2876
2877 /**
2878 * Get a cache key for a foreign DB
2879 */
2880 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2881 $args = array_slice( func_get_args(), 2 );
2882 if ( $prefix ) {
2883 $key = "$db-$prefix:" . implode( ':', $args );
2884 } else {
2885 $key = $db . ':' . implode( ':', $args );
2886 }
2887 return $key;
2888 }
2889
2890 /**
2891 * Get an ASCII string identifying this wiki
2892 * This is used as a prefix in memcached keys
2893 */
2894 function wfWikiID() {
2895 global $wgDBprefix, $wgDBname;
2896 if ( $wgDBprefix ) {
2897 return "$wgDBname-$wgDBprefix";
2898 } else {
2899 return $wgDBname;
2900 }
2901 }
2902
2903 /**
2904 * Split a wiki ID into DB name and table prefix
2905 */
2906 function wfSplitWikiID( $wiki ) {
2907 $bits = explode( '-', $wiki, 2 );
2908 if ( count( $bits ) < 2 ) {
2909 $bits[] = '';
2910 }
2911 return $bits;
2912 }
2913
2914 /**
2915 * Get a Database object.
2916 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2917 * master (for write queries), DB_SLAVE for potentially lagged read
2918 * queries, or an integer >= 0 for a particular server.
2919 *
2920 * @param $groups Mixed: query groups. An array of group names that this query
2921 * belongs to. May contain a single string if the query is only
2922 * in one group.
2923 *
2924 * @param $wiki String: the wiki ID, or false for the current wiki
2925 *
2926 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2927 * will always return the same object, unless the underlying connection or load
2928 * balancer is manually destroyed.
2929 *
2930 * @return DatabaseBase
2931 */
2932 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2933 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2934 }
2935
2936 /**
2937 * Get a load balancer object.
2938 *
2939 * @param $wiki String: wiki ID, or false for the current wiki
2940 * @return LoadBalancer
2941 */
2942 function wfGetLB( $wiki = false ) {
2943 return wfGetLBFactory()->getMainLB( $wiki );
2944 }
2945
2946 /**
2947 * Get the load balancer factory object
2948 * @return LBFactory
2949 */
2950 function &wfGetLBFactory() {
2951 return LBFactory::singleton();
2952 }
2953
2954 /**
2955 * Find a file.
2956 * Shortcut for RepoGroup::singleton()->findFile()
2957 * @param $title String or Title object
2958 * @param $options Associative array of options:
2959 * time: requested time for an archived image, or false for the
2960 * current version. An image object will be returned which was
2961 * created at the specified time.
2962 *
2963 * ignoreRedirect: If true, do not follow file redirects
2964 *
2965 * private: If true, return restricted (deleted) files if the current
2966 * user is allowed to view them. Otherwise, such files will not
2967 * be found.
2968 *
2969 * bypassCache: If true, do not use the process-local cache of File objects
2970 *
2971 * @return File, or false if the file does not exist
2972 */
2973 function wfFindFile( $title, $options = array() ) {
2974 return RepoGroup::singleton()->findFile( $title, $options );
2975 }
2976
2977 /**
2978 * Get an object referring to a locally registered file.
2979 * Returns a valid placeholder object if the file does not exist.
2980 * @param $title Title or String
2981 * @return File, or null if passed an invalid Title
2982 */
2983 function wfLocalFile( $title ) {
2984 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2985 }
2986
2987 /**
2988 * Should low-performance queries be disabled?
2989 *
2990 * @return Boolean
2991 * @codeCoverageIgnore
2992 */
2993 function wfQueriesMustScale() {
2994 global $wgMiserMode;
2995 return $wgMiserMode
2996 || ( SiteStats::pages() > 100000
2997 && SiteStats::edits() > 1000000
2998 && SiteStats::users() > 10000 );
2999 }
3000
3001 /**
3002 * Get the path to a specified script file, respecting file
3003 * extensions; this is a wrapper around $wgScriptExtension etc.
3004 *
3005 * @param $script String: script filename, sans extension
3006 * @return String
3007 */
3008 function wfScript( $script = 'index' ) {
3009 global $wgScriptPath, $wgScriptExtension;
3010 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3011 }
3012
3013 /**
3014 * Get the script URL.
3015 *
3016 * @return script URL
3017 */
3018 function wfGetScriptUrl() {
3019 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3020 #
3021 # as it was called, minus the query string.
3022 #
3023 # Some sites use Apache rewrite rules to handle subdomains,
3024 # and have PHP set up in a weird way that causes PHP_SELF
3025 # to contain the rewritten URL instead of the one that the
3026 # outside world sees.
3027 #
3028 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3029 # provides containing the "before" URL.
3030 return $_SERVER['SCRIPT_NAME'];
3031 } else {
3032 return $_SERVER['URL'];
3033 }
3034 }
3035
3036 /**
3037 * Convenience function converts boolean values into "true"
3038 * or "false" (string) values
3039 *
3040 * @param $value Boolean
3041 * @return String
3042 */
3043 function wfBoolToStr( $value ) {
3044 return $value ? 'true' : 'false';
3045 }
3046
3047 /**
3048 * Load an extension messages file
3049 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3050 * @codeCoverageIgnore
3051 */
3052 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3053 wfDeprecated( __FUNCTION__ );
3054 }
3055
3056 /**
3057 * Get a platform-independent path to the null file, e.g.
3058 * /dev/null
3059 *
3060 * @return string
3061 */
3062 function wfGetNull() {
3063 return wfIsWindows()
3064 ? 'NUL'
3065 : '/dev/null';
3066 }
3067
3068 /**
3069 * Displays a maxlag error
3070 *
3071 * @param $host String: server that lags the most
3072 * @param $lag Integer: maxlag (actual)
3073 * @param $maxLag Integer: maxlag (requested)
3074 */
3075 function wfMaxlagError( $host, $lag, $maxLag ) {
3076 global $wgShowHostnames;
3077 header( 'HTTP/1.1 503 Service Unavailable' );
3078 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3079 header( 'X-Database-Lag: ' . intval( $lag ) );
3080 header( 'Content-Type: text/plain' );
3081 if( $wgShowHostnames ) {
3082 echo "Waiting for $host: $lag seconds lagged\n";
3083 } else {
3084 echo "Waiting for a database server: $lag seconds lagged\n";
3085 }
3086 }
3087
3088 /**
3089 * Throws a warning that $function is deprecated
3090 * @param $function String
3091 * @return null
3092 */
3093 function wfDeprecated( $function ) {
3094 static $functionsWarned = array();
3095 if ( !isset( $functionsWarned[$function] ) ) {
3096 $functionsWarned[$function] = true;
3097 wfWarn( "Use of $function is deprecated.", 2 );
3098 }
3099 }
3100
3101 /**
3102 * Send a warning either to the debug log or in a PHP error depending on
3103 * $wgDevelopmentWarnings
3104 *
3105 * @param $msg String: message to send
3106 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3107 * find the correct caller (1 = function calling wfWarn, ...)
3108 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3109 * is true
3110 */
3111 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3112 $callers = wfDebugBacktrace();
3113 if( isset( $callers[$callerOffset + 1] ) ){
3114 $callerfunc = $callers[$callerOffset + 1];
3115 $callerfile = $callers[$callerOffset];
3116 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3117 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3118 } else {
3119 $file = '(internal function)';
3120 }
3121 $func = '';
3122 if( isset( $callerfunc['class'] ) ) {
3123 $func .= $callerfunc['class'] . '::';
3124 }
3125 if( isset( $callerfunc['function'] ) ) {
3126 $func .= $callerfunc['function'];
3127 }
3128 $msg .= " [Called from $func in $file]";
3129 }
3130
3131 global $wgDevelopmentWarnings;
3132 if ( $wgDevelopmentWarnings ) {
3133 trigger_error( $msg, $level );
3134 } else {
3135 wfDebug( "$msg\n" );
3136 }
3137 }
3138
3139 /**
3140 * Sleep until the worst slave's replication lag is less than or equal to
3141 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3142 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3143 * a no-op if there are no slaves.
3144 *
3145 * Every time the function has to wait for a slave, it will print a message to
3146 * that effect (and then sleep for a little while), so it's probably not best
3147 * to use this outside maintenance scripts in its present form.
3148 *
3149 * @param $maxLag Integer
3150 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3151 * @return null
3152 */
3153 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3154 if( $maxLag ) {
3155 $lb = wfGetLB( $wiki );
3156 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3157 while( $lag > $maxLag ) {
3158 wfSuppressWarnings();
3159 $name = gethostbyaddr( $host );
3160 wfRestoreWarnings();
3161 if( $name !== false ) {
3162 $host = $name;
3163 }
3164 print "Waiting for $host (lagged $lag seconds)...\n";
3165 sleep( $maxLag );
3166 list( $host, $lag ) = $lb->getMaxLag();
3167 }
3168 }
3169 }
3170
3171 /**
3172 * Used to be used for outputting text in the installer/updater
3173 * @deprecated Warnings in 1.19, removal in 1.20
3174 */
3175 function wfOut( $s ) {
3176 global $wgCommandLineMode;
3177 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3178 echo $s;
3179 } else {
3180 echo htmlspecialchars( $s );
3181 }
3182 flush();
3183 }
3184
3185 /**
3186 * Count down from $n to zero on the terminal, with a one-second pause
3187 * between showing each number. For use in command-line scripts.
3188 * @codeCoverageIgnore
3189 */
3190 function wfCountDown( $n ) {
3191 for ( $i = $n; $i >= 0; $i-- ) {
3192 if ( $i != $n ) {
3193 echo str_repeat( "\x08", strlen( $i + 1 ) );
3194 }
3195 echo $i;
3196 flush();
3197 if ( $i ) {
3198 sleep( 1 );
3199 }
3200 }
3201 echo "\n";
3202 }
3203
3204 /**
3205 * Generate a random 32-character hexadecimal token.
3206 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3207 * characters before hashing.
3208 * @codeCoverageIgnore
3209 */
3210 function wfGenerateToken( $salt = '' ) {
3211 $salt = serialize( $salt );
3212 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3213 }
3214
3215 /**
3216 * Replace all invalid characters with -
3217 * @param $name Mixed: filename to process
3218 */
3219 function wfStripIllegalFilenameChars( $name ) {
3220 global $wgIllegalFileChars;
3221 $name = wfBaseName( $name );
3222 $name = preg_replace(
3223 "/[^" . Title::legalChars() . "]" .
3224 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3225 "/",
3226 '-',
3227 $name
3228 );
3229 return $name;
3230 }
3231
3232 /**
3233 * Insert array into another array after the specified *KEY*
3234 * @param $array Array: The array.
3235 * @param $insert Array: The array to insert.
3236 * @param $after Mixed: The key to insert after
3237 */
3238 function wfArrayInsertAfter( $array, $insert, $after ) {
3239 // Find the offset of the element to insert after.
3240 $keys = array_keys( $array );
3241 $offsetByKey = array_flip( $keys );
3242
3243 $offset = $offsetByKey[$after];
3244
3245 // Insert at the specified offset
3246 $before = array_slice( $array, 0, $offset + 1, true );
3247 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
3248
3249 $output = $before + $insert + $after;
3250
3251 return $output;
3252 }
3253
3254 /* Recursively converts the parameter (an object) to an array with the same data */
3255 function wfObjectToArray( $objOrArray, $recursive = true ) {
3256 $array = array();
3257 if( is_object( $objOrArray ) ) {
3258 $objOrArray = get_object_vars( $objOrArray );
3259 }
3260 foreach ( $objOrArray as $key => $value ) {
3261 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
3262 $value = wfObjectToArray( $value );
3263 }
3264
3265 $array[$key] = $value;
3266 }
3267
3268 return $array;
3269 }
3270
3271 /**
3272 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3273 * @return Integer value memory was set to.
3274 */
3275 function wfMemoryLimit() {
3276 global $wgMemoryLimit;
3277 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3278 if( $memlimit != -1 ) {
3279 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3280 if( $conflimit == -1 ) {
3281 wfDebug( "Removing PHP's memory limit\n" );
3282 wfSuppressWarnings();
3283 ini_set( 'memory_limit', $conflimit );
3284 wfRestoreWarnings();
3285 return $conflimit;
3286 } elseif ( $conflimit > $memlimit ) {
3287 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3288 wfSuppressWarnings();
3289 ini_set( 'memory_limit', $conflimit );
3290 wfRestoreWarnings();
3291 return $conflimit;
3292 }
3293 }
3294 return $memlimit;
3295 }
3296
3297 /**
3298 * Converts shorthand byte notation to integer form
3299 * @param $string String
3300 * @return Integer
3301 */
3302 function wfShorthandToInteger( $string = '' ) {
3303 $string = trim( $string );
3304 if( $string === '' ) {
3305 return -1;
3306 }
3307 $last = $string[strlen( $string ) - 1];
3308 $val = intval( $string );
3309 switch( $last ) {
3310 case 'g':
3311 case 'G':
3312 $val *= 1024;
3313 // break intentionally missing
3314 case 'm':
3315 case 'M':
3316 $val *= 1024;
3317 // break intentionally missing
3318 case 'k':
3319 case 'K':
3320 $val *= 1024;
3321 }
3322
3323 return $val;
3324 }
3325
3326 /**
3327 * Get the normalised IETF language tag
3328 * See unit test for examples.
3329 * @param $code String: The language code.
3330 * @return $langCode String: The language code which complying with BCP 47 standards.
3331 */
3332 function wfBCP47( $code ) {
3333 $codeSegment = explode( '-', $code );
3334 foreach ( $codeSegment as $segNo => $seg ) {
3335 if ( count( $codeSegment ) > 0 ) {
3336 // when previous segment is x, it is a private segment and should be lc
3337 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3338 $codeBCP[$segNo] = strtolower( $seg );
3339 // ISO 3166 country code
3340 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3341 $codeBCP[$segNo] = strtoupper( $seg );
3342 // ISO 15924 script code
3343 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3344 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3345 // Use lowercase for other cases
3346 } else {
3347 $codeBCP[$segNo] = strtolower( $seg );
3348 }
3349 } else {
3350 // Use lowercase for single segment
3351 $codeBCP[$segNo] = strtolower( $seg );
3352 }
3353 }
3354 $langCode = implode( '-', $codeBCP );
3355 return $langCode;
3356 }
3357
3358 function wfArrayMap( $function, $input ) {
3359 $ret = array_map( $function, $input );
3360 foreach ( $ret as $key => $value ) {
3361 $taint = istainted( $input[$key] );
3362 if ( $taint ) {
3363 taint( $ret[$key], $taint );
3364 }
3365 }
3366 return $ret;
3367 }
3368
3369
3370 /**
3371 * Get a cache object.
3372 * @param $inputType Cache type, one the the CACHE_* constants.
3373 *
3374 * @return BagOStuff
3375 */
3376 function wfGetCache( $inputType ) {
3377 return ObjectCache::getInstance( $inputType );
3378 }
3379
3380 /** Get the main cache object */
3381 function wfGetMainCache() {
3382 global $wgMainCacheType;
3383 return ObjectCache::getInstance( $wgMainCacheType );
3384 }
3385
3386 /** Get the cache object used by the message cache */
3387 function wfGetMessageCacheStorage() {
3388 global $wgMessageCacheType;
3389 return ObjectCache::getInstance( $wgMessageCacheType );
3390 }
3391
3392 /** Get the cache object used by the parser cache */
3393 function wfGetParserCacheStorage() {
3394 global $wgParserCacheType;
3395 return ObjectCache::getInstance( $wgParserCacheType );
3396 }
3397