3 * Global functions used everywhere
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
11 require_once dirname( __FILE__
) . '/normal/UtfNormalUtil.php';
13 // Hide compatibility functions from Doxygen
17 * Compatibility functions
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.
23 if( !function_exists( 'iconv' ) ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if ( substr( $to, -8 ) == '//IGNORE' ) {
29 $to = substr( $to, 0, strlen( $to ) - 8 );
31 if( strcasecmp( $from, $to ) == 0 ) {
34 if( strcasecmp( $from, 'utf-8' ) == 0 ) {
35 return utf8_decode( $string );
37 if( strcasecmp( $to, 'utf-8' ) == 0 ) {
38 return utf8_encode( $string );
44 if ( !function_exists( 'mb_substr' ) ) {
46 * Fallback implementation for mb_substr, hardcoded to UTF-8.
47 * Attempts to be at least _moderately_ efficient; best optimized
48 * for relatively small offset and count values -- about 5x slower
49 * than native mb_string in my testing.
51 * Larger offsets are still fairly efficient for Latin text, but
52 * can be up to 100x slower than native if the text is heavily
53 * multibyte and we have to slog through a few hundred kb.
55 function mb_substr( $str, $start, $count='end' ) {
57 $split = mb_substr_split_unicode( $str, intval( $start ) );
58 $str = substr( $str, $split );
61 if( $count !== 'end' ) {
62 $split = mb_substr_split_unicode( $str, intval( $count ) );
63 $str = substr( $str, 0, $split );
69 function mb_substr_split_unicode( $str, $splitPos ) {
70 if( $splitPos == 0 ) {
74 $byteLen = strlen( $str );
77 if( $splitPos > 256 ) {
78 // Optimize large string offsets by skipping ahead N bytes.
79 // This will cut out most of our slow time on Latin-based text,
80 // and 1/2 to 1/3 on East European and Asian scripts.
82 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
85 $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
91 while( $charPos++
< $splitPos ) {
93 // Move past any tail bytes
94 while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
99 $splitPosX = $splitPos +
1;
100 $charPos = 0; // relative to end of string; we don't care about the actual char position here
102 while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
104 // Move past any tail bytes
105 while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
115 if ( !function_exists( 'mb_strlen' ) ) {
117 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
119 * @param string $enc optional encoding; ignored
122 function mb_strlen( $str, $enc = '' ) {
123 $counts = count_chars( $str );
127 for( $i = 0; $i < 0x80; $i++
) {
128 $total +
= $counts[$i];
131 // Count multibyte sequence heads
132 for( $i = 0xc0; $i < 0xff; $i++
) {
133 $total +
= $counts[$i];
140 if( !function_exists( 'mb_strpos' ) ) {
142 * Fallback implementation of mb_strpos, hardcoded to UTF-8.
143 * @param $haystack String
144 * @param $needle String
145 * @param $offset String: optional start position
146 * @param $encoding String: optional encoding; ignored
149 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
150 $needle = preg_quote( $needle, '/' );
153 preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
155 if( isset( $ar[0][1] ) ) {
163 if( !function_exists( 'mb_strrpos' ) ) {
165 * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
166 * @param $haystack String
167 * @param $needle String
168 * @param $offset String: optional start position
169 * @param $encoding String: optional encoding; ignored
172 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
173 $needle = preg_quote( $needle, '/' );
176 preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE
, $offset );
178 if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
179 isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
180 return $ar[0][count( $ar[0] ) - 1][1];
187 // Support for Wietse Venema's taint feature
188 if ( !function_exists( 'istainted' ) ) {
189 function istainted( $var ) {
192 function taint( $var, $level = 0 ) {}
193 function untaint( $var, $level = 0 ) {}
194 define( 'TC_HTML', 1 );
195 define( 'TC_SHELL', 1 );
196 define( 'TC_MYSQL', 1 );
197 define( 'TC_PCRE', 1 );
198 define( 'TC_SELF', 1 );
204 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
206 function wfArrayDiff2( $a, $b ) {
207 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
209 function wfArrayDiff2_cmp( $a, $b ) {
210 if ( !is_array( $a ) ) {
211 return strcmp( $a, $b );
212 } elseif ( count( $a ) !== count( $b ) ) {
213 return count( $a ) < count( $b ) ?
-1 : 1;
217 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
218 $cmp = strcmp( $valueA, $valueB );
228 * Seed Mersenne Twister
229 * No-op for compatibility; only necessary in PHP < 4.2.0
230 * @deprecated. Remove in 1.18
232 function wfSeedRandom() {
233 wfDeprecated(__FUNCTION__
);
237 * Get a random decimal value between 0 and 1, in a way
238 * not likely to give duplicate values for any realistic
239 * number of articles.
243 function wfRandom() {
244 # The maximum random value is "only" 2^31-1, so get two random
245 # values to reduce the chance of dupes
246 $max = mt_getrandmax() +
1;
247 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
248 / $max / $max, 12, '.', '' );
253 * We want some things to be included as literal characters in our title URLs
254 * for prettiness, which urlencode encodes by default. According to RFC 1738,
255 * all of the following should be safe:
259 * But + is not safe because it's used to indicate a space; &= are only safe in
260 * paths and not in queries (and we don't distinguish here); ' seems kind of
261 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
262 * is reserved, we don't care. So the list we unescape is:
266 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
267 * so no fancy : for IIS7.
269 * %2F in the page titles seems to fatally break for some reason.
274 function wfUrlencode( $s ) {
276 if ( is_null( $needle ) ) {
277 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
278 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
283 $s = urlencode( $s );
286 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
294 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
295 * In normal operation this is a NOP.
297 * Controlling globals:
298 * $wgDebugLogFile - points to the log file
299 * $wgProfileOnly - if set, normal debug messages will not be recorded.
300 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
301 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
303 * @param $text String
304 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
306 function wfDebug( $text, $logonly = false ) {
307 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
308 global $wgDebugLogPrefix, $wgShowDebug;
309 static $recursion = 0;
311 static $cache = array(); // Cache of unoutputted messages
312 $text = wfDebugTimer() . $text;
314 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
315 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
319 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
322 if ( !isset( $wgOut ) ) {
325 if ( !StubObject
::isRealObject( $wgOut ) ) {
334 // add the message and possible cached ones to the output
335 array_map( array( $wgOut, 'debug' ), $cache );
338 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
339 # Strip unprintables; they can switch terminal modes when binary data
340 # gets dumped, which is pretty annoying.
341 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
342 $text = $wgDebugLogPrefix . $text;
343 wfErrorLog( $text, $wgDebugLogFile );
347 function wfDebugTimer() {
348 global $wgDebugTimestamps;
349 if ( !$wgDebugTimestamps ) {
352 static $start = null;
354 if ( $start === null ) {
355 $start = microtime( true );
356 $prefix = "\n$start";
358 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
361 return $prefix . ' ';
365 * Send a line giving PHP memory usage.
366 * @param $exact Bool: print exact values instead of kilobytes (default: false)
368 function wfDebugMem( $exact = false ) {
369 $mem = memory_get_usage();
371 $mem = floor( $mem / 1024 ) . ' kilobytes';
375 wfDebug( "Memory usage: $mem\n" );
379 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
380 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
382 * @param $logGroup String
383 * @param $text String
384 * @param $public Bool: whether to log the event in the public log if no private
385 * log file is specified, (default true)
387 function wfDebugLog( $logGroup, $text, $public = true ) {
388 global $wgDebugLogGroups, $wgShowHostnames;
389 $text = trim( $text ) . "\n";
390 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
391 $time = wfTimestamp( TS_DB
);
393 if ( $wgShowHostnames ) {
394 $host = wfHostname();
398 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
399 } elseif ( $public === true ) {
400 wfDebug( $text, true );
405 * Log for database errors
406 * @param $text String: database error message.
408 function wfLogDBError( $text ) {
409 global $wgDBerrorLog, $wgDBname;
410 if ( $wgDBerrorLog ) {
411 $host = trim(`hostname`
);
412 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
413 wfErrorLog( $text, $wgDBerrorLog );
418 * Log to a file without getting "file size exceeded" signals.
420 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
421 * send lines to the specified port, prefixed by the specified prefix and a space.
423 function wfErrorLog( $text, $file ) {
424 if ( substr( $file, 0, 4 ) == 'udp:' ) {
425 # Needs the sockets extension
426 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
427 // IPv6 bracketed host
429 $port = intval( $m[3] );
430 $prefix = isset( $m[4] ) ?
$m[4] : false;
432 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
434 if ( !IP
::isIPv4( $host ) ) {
435 $host = gethostbyname( $host );
437 $port = intval( $m[3] );
438 $prefix = isset( $m[4] ) ?
$m[4] : false;
441 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
443 // Clean it up for the multiplexer
444 if ( strval( $prefix ) !== '' ) {
445 $text = preg_replace( '/^/m', $prefix . ' ', $text );
446 if ( substr( $text, -1 ) != "\n" ) {
451 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
455 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
456 socket_close( $sock );
458 wfSuppressWarnings();
459 $exists = file_exists( $file );
460 $size = $exists ?
filesize( $file ) : false;
461 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
462 error_log( $text, 3, $file );
471 function wfLogProfilingData() {
472 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
473 global $wgProfiler, $wgProfileLimit, $wgUser;
474 # Profiling must actually be enabled...
475 if( is_null( $wgProfiler ) ) {
478 # Get total page request time
480 $elapsed = $now - $wgRequestTime;
481 # Only show pages that longer than $wgProfileLimit time (default is 0)
482 if( $elapsed <= $wgProfileLimit ) {
485 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
487 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
488 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
490 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
491 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
493 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
494 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
497 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
499 // Don't unstub $wgUser at this late stage just for statistics purposes
500 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
501 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
504 $log = sprintf( "%s\t%04.3f\t%s\n",
505 gmdate( 'YmdHis' ), $elapsed,
506 urldecode( $wgRequest->getRequestURL() . $forward ) );
507 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
508 wfErrorLog( $log . $prof, $wgDebugLogFile );
513 * Check if the wiki read-only lock file is present. This can be used to lock
514 * off editing functions, but doesn't guarantee that the database will not be
518 function wfReadOnly() {
519 global $wgReadOnlyFile, $wgReadOnly;
521 if ( !is_null( $wgReadOnly ) ) {
522 return (bool)$wgReadOnly;
524 if ( $wgReadOnlyFile == '' ) {
527 // Set $wgReadOnly for faster access next time
528 if ( is_file( $wgReadOnlyFile ) ) {
529 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
533 return (bool)$wgReadOnly;
536 function wfReadOnlyReason() {
543 * Return a Language object from $langcode
544 * @param $langcode Mixed: either:
545 * - a Language object
546 * - code of the language to get the message for, if it is
547 * a valid code create a language for that language, if
548 * it is a string but not a valid code then make a basic
550 * - a boolean: if it's false then use the current users
551 * language (as a fallback for the old parameter
552 * functionality), or if it is true then use the wikis
553 * @return Language object
555 function wfGetLangObj( $langcode = false ) {
556 # Identify which language to get or create a language object for.
557 # Using is_object here due to Stub objects.
558 if( is_object( $langcode ) ) {
559 # Great, we already have the object (hopefully)!
563 global $wgContLang, $wgLanguageCode;
564 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
565 # $langcode is the language code of the wikis content language object.
566 # or it is a boolean and value is true
571 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
572 # $langcode is the language code of user language object.
573 # or it was a boolean and value is false
577 $validCodes = array_keys( Language
::getLanguageNames() );
578 if( in_array( $langcode, $validCodes ) ) {
579 # $langcode corresponds to a valid language.
580 return Language
::factory( $langcode );
583 # $langcode is a string, but not a valid language code; use content language.
584 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
589 * Use this instead of $wgContLang, when working with user interface.
590 * User interface is currently hard coded according to wiki content language
591 * in many ways, especially regarding to text direction. There is lots stuff
592 * to fix, hence this function to keep the old behaviour unless the global
593 * $wgBetterDirectionality is enabled (or removed when everything works).
595 function wfUILang() {
596 global $wgBetterDirectionality;
597 return wfGetLangObj( !$wgBetterDirectionality );
601 * This is the new function for getting translated interface messages.
602 * See the Message class for documentation how to use them.
603 * The intention is that this function replaces all old wfMsg* functions.
604 * @param $key \string Message key.
605 * Varargs: normal message parameters.
606 * @return \type{Message}
609 function wfMessage( $key /*...*/) {
610 $params = func_get_args();
611 array_shift( $params );
612 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
613 $params = $params[0];
615 return new Message( $key, $params );
619 * Get a message from anywhere, for the current user language.
621 * Use wfMsgForContent() instead if the message should NOT
622 * change depending on the user preferences.
624 * @param $key String: lookup key for the message, usually
625 * defined in languages/Language.php
627 * This function also takes extra optional parameters (not
628 * shown in the function definition), which can be used to
629 * insert variable text into the predefined message.
631 function wfMsg( $key ) {
632 $args = func_get_args();
633 array_shift( $args );
634 return wfMsgReal( $key, $args, true );
638 * Same as above except doesn't transform the message
640 function wfMsgNoTrans( $key ) {
641 $args = func_get_args();
642 array_shift( $args );
643 return wfMsgReal( $key, $args, true, false, false );
647 * Get a message from anywhere, for the current global language
648 * set with $wgLanguageCode.
650 * Use this if the message should NOT change dependent on the
651 * language set in the user's preferences. This is the case for
652 * most text written into logs, as well as link targets (such as
653 * the name of the copyright policy page). Link titles, on the
654 * other hand, should be shown in the UI language.
656 * Note that MediaWiki allows users to change the user interface
657 * language in their preferences, but a single installation
658 * typically only contains content in one language.
660 * Be wary of this distinction: If you use wfMsg() where you should
661 * use wfMsgForContent(), a user of the software may have to
662 * customize potentially hundreds of messages in
663 * order to, e.g., fix a link in every possible language.
665 * @param $key String: lookup key for the message, usually
666 * defined in languages/Language.php
668 function wfMsgForContent( $key ) {
669 global $wgForceUIMsgAsContentMsg;
670 $args = func_get_args();
671 array_shift( $args );
673 if( is_array( $wgForceUIMsgAsContentMsg ) &&
674 in_array( $key, $wgForceUIMsgAsContentMsg ) )
678 return wfMsgReal( $key, $args, true, $forcontent );
682 * Same as above except doesn't transform the message
684 function wfMsgForContentNoTrans( $key ) {
685 global $wgForceUIMsgAsContentMsg;
686 $args = func_get_args();
687 array_shift( $args );
689 if( is_array( $wgForceUIMsgAsContentMsg ) &&
690 in_array( $key, $wgForceUIMsgAsContentMsg ) )
694 return wfMsgReal( $key, $args, true, $forcontent, false );
698 * Get a message from the language file, for the UI elements
700 function wfMsgNoDB( $key ) {
701 $args = func_get_args();
702 array_shift( $args );
703 return wfMsgReal( $key, $args, false );
707 * Get a message from the language file, for the content
709 function wfMsgNoDBForContent( $key ) {
710 global $wgForceUIMsgAsContentMsg;
711 $args = func_get_args();
712 array_shift( $args );
714 if( is_array( $wgForceUIMsgAsContentMsg ) &&
715 in_array( $key, $wgForceUIMsgAsContentMsg ) )
719 return wfMsgReal( $key, $args, false, $forcontent );
724 * Really get a message
725 * @param $key String: key to get.
727 * @param $useDB Boolean
728 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
729 * @param $transform Boolean: Whether or not to transform the message.
730 * @return String: the requested message.
732 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
733 wfProfileIn( __METHOD__
);
734 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
735 $message = wfMsgReplaceArgs( $message, $args );
736 wfProfileOut( __METHOD__
);
741 * This function provides the message source for messages to be edited which are *not* stored in the database.
742 * @param $key String:
744 function wfMsgWeirdKey( $key ) {
745 $source = wfMsgGetKey( $key, false, true, false );
746 if ( wfEmptyMsg( $key, $source ) ) {
754 * Fetch a message string value, but don't replace any keys yet.
757 * @param $langCode String: Code of the language to get the message for, or
758 * behaves as a content language switch if it is a boolean.
759 * @param $transform Boolean: whether to parse magic words, etc.
762 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
763 global $wgMessageCache;
765 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
767 if ( !is_object( $wgMessageCache ) ) {
768 throw new MWException( 'Trying to get message before message cache is initialised' );
771 $message = $wgMessageCache->get( $key, $useDB, $langCode );
772 if( $message === false ) {
773 $message = '<' . htmlspecialchars( $key ) . '>';
774 } elseif ( $transform ) {
775 $message = $wgMessageCache->transform( $message );
781 * Replace message parameter keys on the given formatted output.
783 * @param $message String
788 function wfMsgReplaceArgs( $message, $args ) {
789 # Fix windows line-endings
790 # Some messages are split with explode("\n", $msg)
791 $message = str_replace( "\r", '', $message );
794 if ( count( $args ) ) {
795 if ( is_array( $args[0] ) ) {
796 $args = array_values( $args[0] );
798 $replacementKeys = array();
799 foreach( $args as $n => $param ) {
800 $replacementKeys['$' . ( $n +
1 )] = $param;
802 $message = strtr( $message, $replacementKeys );
809 * Return an HTML-escaped version of a message.
810 * Parameter replacements, if any, are done *after* the HTML-escaping,
811 * so parameters may contain HTML (eg links or form controls). Be sure
812 * to pre-escape them if you really do want plaintext, or just wrap
813 * the whole thing in htmlspecialchars().
816 * @param string ... parameters
819 function wfMsgHtml( $key ) {
820 $args = func_get_args();
821 array_shift( $args );
822 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
826 * Return an HTML version of message
827 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
828 * so parameters may contain HTML (eg links or form controls). Be sure
829 * to pre-escape them if you really do want plaintext, or just wrap
830 * the whole thing in htmlspecialchars().
833 * @param string ... parameters
836 function wfMsgWikiHtml( $key ) {
838 $args = func_get_args();
839 array_shift( $args );
840 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
844 * Returns message in the requested format
845 * @param $key String: key of the message
846 * @param $options Array: processing rules. Can take the following options:
847 * <i>parse</i>: parses wikitext to HTML
848 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
849 * p's added by parser or tidy
850 * <i>escape</i>: filters message through htmlspecialchars
851 * <i>escapenoentities</i>: same, but allows entity references like   through
852 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
853 * <i>parsemag</i>: transform the message using magic phrases
854 * <i>content</i>: fetch message for content language instead of interface
855 * Also can accept a single associative argument, of the form 'language' => 'xx':
856 * <i>language</i>: Language object or language code to fetch message for
857 * (overriden by <i>content</i>), its behaviour with parser, parseinline
858 * and parsemag is undefined.
859 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
861 function wfMsgExt( $key, $options ) {
864 $args = func_get_args();
865 array_shift( $args );
866 array_shift( $args );
867 $options = (array)$options;
869 foreach( $options as $arrayKey => $option ) {
870 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
871 # An unknown index, neither numeric nor "language"
872 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
873 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
874 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
875 'replaceafter', 'parsemag', 'content' ) ) ) {
876 # A numeric index with unknown value
877 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
881 if( in_array( 'content', $options, true ) ) {
884 } elseif( array_key_exists( 'language', $options ) ) {
886 $langCode = wfGetLangObj( $options['language'] );
892 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
894 if( !in_array( 'replaceafter', $options, true ) ) {
895 $string = wfMsgReplaceArgs( $string, $args );
898 if( in_array( 'parse', $options, true ) ) {
899 $string = $wgOut->parse( $string, true, !$forContent );
900 } elseif ( in_array( 'parseinline', $options, true ) ) {
901 $string = $wgOut->parse( $string, true, !$forContent );
903 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
906 } elseif ( in_array( 'parsemag', $options, true ) ) {
907 global $wgMessageCache;
908 if ( isset( $wgMessageCache ) ) {
909 $string = $wgMessageCache->transform( $string,
911 is_object( $langCode ) ?
$langCode : null );
915 if ( in_array( 'escape', $options, true ) ) {
916 $string = htmlspecialchars ( $string );
917 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
918 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
921 if( in_array( 'replaceafter', $options, true ) ) {
922 $string = wfMsgReplaceArgs( $string, $args );
930 * Just like exit() but makes a note of it.
931 * Commits open transactions except if the error parameter is set
933 * @deprecated Please return control to the caller or throw an exception. Will
934 * be removed in 1.19.
936 function wfAbruptExit( $error = false ) {
937 static $called = false;
943 wfDeprecated( __FUNCTION__
);
944 $bt = wfDebugBacktrace();
946 for( $i = 0; $i < count( $bt ); $i++
) {
947 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
948 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
949 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
952 wfDebug( "WARNING: Abrupt exit\n" );
955 wfLogProfilingData();
958 wfGetLB()->closeAll();
964 * @deprecated Please return control the caller or throw an exception. Will
965 * be removed in 1.19.
967 function wfErrorExit() {
968 wfDeprecated( __FUNCTION__
);
969 wfAbruptExit( true );
973 * Print a simple message and die, returning nonzero to the shell if any.
974 * Plain die() fails to return nonzero to the shell if you pass a string.
977 function wfDie( $msg = '' ) {
983 * Throw a debugging exception. This function previously once exited the process,
984 * but now throws an exception instead, with similar results.
986 * @param $msg String: message shown when dieing.
988 function wfDebugDieBacktrace( $msg = '' ) {
989 throw new MWException( $msg );
993 * Fetch server name for use in error reporting etc.
994 * Use real server name if available, so we know which machine
995 * in a server farm generated the current page.
998 function wfHostname() {
1000 if ( is_null( $host ) ) {
1001 if ( function_exists( 'posix_uname' ) ) {
1002 // This function not present on Windows
1003 $uname = @posix_uname
();
1007 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1008 $host = $uname['nodename'];
1009 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1010 # Windows computer name
1011 $host = getenv( 'COMPUTERNAME' );
1013 # This may be a virtual server.
1014 $host = $_SERVER['SERVER_NAME'];
1021 * Returns a HTML comment with the elapsed time since request.
1022 * This method has no side effects.
1025 function wfReportTime() {
1026 global $wgRequestTime, $wgShowHostnames;
1029 $elapsed = $now - $wgRequestTime;
1031 return $wgShowHostnames
1032 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1033 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1037 * Safety wrapper for debug_backtrace().
1039 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1040 * murky circumstances, which may be triggered in part by stub objects
1041 * or other fancy talkin'.
1043 * Will return an empty array if Zend Optimizer is detected or if
1044 * debug_backtrace is disabled, otherwise the output from
1045 * debug_backtrace() (trimmed).
1047 * @return array of backtrace information
1049 function wfDebugBacktrace() {
1050 static $disabled = null;
1052 if( extension_loaded( 'Zend Optimizer' ) ) {
1053 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1057 if ( is_null( $disabled ) ) {
1059 $functions = explode( ',', ini_get( 'disable_functions' ) );
1060 $functions = array_map( 'trim', $functions );
1061 $functions = array_map( 'strtolower', $functions );
1062 if ( in_array( 'debug_backtrace', $functions ) ) {
1063 wfDebug( "debug_backtrace is in disabled_functions\n" );
1071 return array_slice( debug_backtrace(), 1 );
1074 function wfBacktrace() {
1075 global $wgCommandLineMode;
1077 if ( $wgCommandLineMode ) {
1082 $backtrace = wfDebugBacktrace();
1083 foreach( $backtrace as $call ) {
1084 if( isset( $call['file'] ) ) {
1085 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1086 $file = $f[count( $f ) - 1];
1090 if( isset( $call['line'] ) ) {
1091 $line = $call['line'];
1095 if ( $wgCommandLineMode ) {
1096 $msg .= "$file line $line calls ";
1098 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1100 if( !empty( $call['class'] ) ) {
1101 $msg .= $call['class'] . '::';
1103 $msg .= $call['function'] . '()';
1105 if ( $wgCommandLineMode ) {
1111 if ( $wgCommandLineMode ) {
1121 /* Some generic result counters, pulled out of SearchEngine */
1127 function wfShowingResults( $offset, $limit ) {
1131 array( 'parseinline' ),
1132 $wgLang->formatNum( $limit ),
1133 $wgLang->formatNum( $offset +
1 )
1140 function wfShowingResultsNum( $offset, $limit, $num ) {
1143 'showingresultsnum',
1144 array( 'parseinline' ),
1145 $wgLang->formatNum( $limit ),
1146 $wgLang->formatNum( $offset +
1 ),
1147 $wgLang->formatNum( $num )
1152 * Generate (prev x| next x) (20|50|100...) type links for paging
1153 * @param $offset String
1154 * @param $limit Integer
1155 * @param $link String
1156 * @param $query String: optional URL query parameter string
1157 * @param $atend Bool: optional param for specified if this is the last page
1159 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1161 $fmtLimit = $wgLang->formatNum( $limit );
1162 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1163 # Get prev/next link display text
1164 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1165 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1166 # Get prev/next link title text
1167 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1168 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1169 # Fetch the title object
1170 if( is_object( $link ) ) {
1173 $title = Title
::newFromText( $link );
1174 if( is_null( $title ) ) {
1178 # Make 'previous' link
1179 if( 0 != $offset ) {
1180 $po = $offset - $limit;
1181 $po = max( $po, 0 );
1182 $q = "limit={$limit}&offset={$po}";
1183 if( $query != '' ) {
1186 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1191 $no = $offset +
$limit;
1192 $q = "limit={$limit}&offset={$no}";
1193 if( $query != '' ) {
1199 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1201 # Make links to set number of items per page
1202 $nums = $wgLang->pipeList( array(
1203 wfNumLink( $offset, 20, $title, $query ),
1204 wfNumLink( $offset, 50, $title, $query ),
1205 wfNumLink( $offset, 100, $title, $query ),
1206 wfNumLink( $offset, 250, $title, $query ),
1207 wfNumLink( $offset, 500, $title, $query )
1209 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1213 * Generate links for (20|50|100...) items-per-page links
1214 * @param $offset String
1215 * @param $limit Integer
1216 * @param $title Title
1217 * @param $query String: optional URL query parameter string
1219 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1221 if( $query == '' ) {
1226 $q .= "limit={$limit}&offset={$offset}";
1227 $fmtLimit = $wgLang->formatNum( $limit );
1228 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1229 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1235 * @todo FIXME: we may want to blacklist some broken browsers
1237 * @return bool Whereas client accept gzip compression
1239 function wfClientAcceptsGzip() {
1240 static $result = null;
1241 if ( $result === null ) {
1243 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1244 # FIXME: we may want to blacklist some broken browsers
1247 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1248 $_SERVER['HTTP_ACCEPT_ENCODING'],
1252 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1256 wfDebug( " accepts gzip\n" );
1265 * Obtain the offset and limit values from the request string;
1266 * used in special pages
1268 * @param $deflimit Default limit if none supplied
1269 * @param $optionname Name of a user preference to check against
1273 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1275 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1279 * Escapes the given text so that it may be output using addWikiText()
1280 * without any linking, formatting, etc. making its way through. This
1281 * is achieved by substituting certain characters with HTML entities.
1282 * As required by the callers, <nowiki> is not used. It currently does
1283 * not filter out characters which have special meaning only at the
1284 * start of a line, such as "*".
1286 * @param $text String: text to be escaped
1288 function wfEscapeWikiText( $text ) {
1289 $text = str_replace(
1290 array( '[', '|', ']', '\'', 'ISBN ',
1291 'RFC ', '://', "\n=", '{{', '}}' ),
1292 array( '[', '|', ']', ''', 'ISBN ',
1293 'RFC ', '://', "\n=", '{{', '}}' ),
1294 htmlspecialchars( $text )
1302 function wfQuotedPrintable( $string, $charset = '' ) {
1303 # Probably incomplete; see RFC 2045
1304 if( empty( $charset ) ) {
1305 global $wgInputEncoding;
1306 $charset = $wgInputEncoding;
1308 $charset = strtoupper( $charset );
1309 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1311 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1312 $replace = $illegal . '\t ?_';
1313 if( !preg_match( "/[$illegal]/", $string ) ) {
1316 $out = "=?$charset?Q?";
1317 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1328 return microtime( true );
1332 * Sets dest to source and returns the original value of dest
1333 * If source is NULL, it just returns the value, it doesn't set the variable
1335 function wfSetVar( &$dest, $source ) {
1337 if ( !is_null( $source ) ) {
1344 * As for wfSetVar except setting a bit
1346 function wfSetBit( &$dest, $bit, $state = true ) {
1347 $temp = (bool)( $dest & $bit );
1348 if ( !is_null( $state ) ) {
1359 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1360 * "days=7&limit=100". Options in the first array override options in the second.
1361 * Options set to "" will not be output.
1363 function wfArrayToCGI( $array1, $array2 = null ) {
1364 if ( !is_null( $array2 ) ) {
1365 $array1 = $array1 +
$array2;
1369 foreach ( $array1 as $key => $value ) {
1370 if ( $value !== '' ) {
1374 if ( is_array( $value ) ) {
1376 foreach ( $value as $v ) {
1377 $cgi .= ( $firstTime ?
'' : '&') .
1378 urlencode( $key . '[]' ) . '=' .
1383 if ( is_object( $value ) ) {
1384 $value = $value->__toString();
1386 $cgi .= urlencode( $key ) . '=' .
1387 urlencode( $value );
1395 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1396 * its argument and returns the same string in array form. This allows compa-
1397 * tibility with legacy functions that accept raw query strings instead of nice
1398 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1399 * valid query strings, or it will explode.
1401 * @param $query String: query string
1402 * @return array Array version of input
1404 function wfCgiToArray( $query ) {
1405 if( isset( $query[0] ) && $query[0] == '?' ) {
1406 $query = substr( $query, 1 );
1408 $bits = explode( '&', $query );
1410 foreach( $bits as $bit ) {
1414 list( $key, $value ) = explode( '=', $bit );
1415 $key = urldecode( $key );
1416 $value = urldecode( $value );
1417 $ret[$key] = $value;
1423 * Append a query string to an existing URL, which may or may not already
1424 * have query string parameters already. If so, they will be combined.
1426 * @param $url String
1427 * @param $query Mixed: string or associative array
1430 function wfAppendQuery( $url, $query ) {
1431 if ( is_array( $query ) ) {
1432 $query = wfArrayToCGI( $query );
1434 if( $query != '' ) {
1435 if( false === strpos( $url, '?' ) ) {
1446 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1447 * and $wgProto are correct.
1449 * @todo this won't work with current-path-relative URLs
1450 * like "subdir/foo.html", etc.
1452 * @param $url String: either fully-qualified or a local path + query
1453 * @return string Fully-qualified URL
1455 function wfExpandUrl( $url ) {
1456 if( substr( $url, 0, 2 ) == '//' ) {
1458 return $wgProto . ':' . $url;
1459 } elseif( substr( $url, 0, 1 ) == '/' ) {
1461 return $wgServer . $url;
1468 * Windows-compatible version of escapeshellarg()
1469 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1470 * function puts single quotes in regardless of OS.
1472 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1473 * earlier distro releases of PHP)
1475 function wfEscapeShellArg( ) {
1476 wfInitShellLocale();
1478 $args = func_get_args();
1481 foreach ( $args as $arg ) {
1488 if ( wfIsWindows() ) {
1489 // Escaping for an MSVC-style command line parser
1490 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1491 // Double the backslashes before any double quotes. Escape the double quotes.
1492 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1495 foreach ( $tokens as $token ) {
1496 if ( $iteration %
2 == 1 ) {
1497 // Delimiter, a double quote preceded by zero or more slashes
1498 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1499 } elseif ( $iteration %
4 == 2 ) {
1500 // ^ in $token will be outside quotes, need to be escaped
1501 $arg .= str_replace( '^', '^^', $token );
1502 } else { // $iteration % 4 == 0
1503 // ^ in $token will appear inside double quotes, so leave as is
1508 // Double the backslashes before the end of the string, because
1509 // we will soon add a quote
1511 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1512 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1515 // Add surrounding quotes
1516 $retVal .= '"' . $arg . '"';
1518 $retVal .= escapeshellarg( $arg );
1525 * wfMerge attempts to merge differences between three texts.
1526 * Returns true for a clean merge and false for failure or a conflict.
1528 function wfMerge( $old, $mine, $yours, &$result ) {
1531 # This check may also protect against code injection in
1532 # case of broken installations.
1533 wfSuppressWarnings();
1534 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1535 wfRestoreWarnings();
1538 wfDebug( "diff3 not found\n" );
1542 # Make temporary files
1544 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1545 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1546 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1548 fwrite( $oldtextFile, $old );
1549 fclose( $oldtextFile );
1550 fwrite( $mytextFile, $mine );
1551 fclose( $mytextFile );
1552 fwrite( $yourtextFile, $yours );
1553 fclose( $yourtextFile );
1555 # Check for a conflict
1556 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1557 wfEscapeShellArg( $mytextName ) . ' ' .
1558 wfEscapeShellArg( $oldtextName ) . ' ' .
1559 wfEscapeShellArg( $yourtextName );
1560 $handle = popen( $cmd, 'r' );
1562 if( fgets( $handle, 1024 ) ) {
1570 $cmd = $wgDiff3 . ' -a -e --merge ' .
1571 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1572 $handle = popen( $cmd, 'r' );
1575 $data = fread( $handle, 8192 );
1576 if ( strlen( $data ) == 0 ) {
1582 unlink( $mytextName );
1583 unlink( $oldtextName );
1584 unlink( $yourtextName );
1586 if ( $result === '' && $old !== '' && !$conflict ) {
1587 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1594 * Returns unified plain-text diff of two texts.
1595 * Useful for machine processing of diffs.
1596 * @param $before String: the text before the changes.
1597 * @param $after String: the text after the changes.
1598 * @param $params String: command-line options for the diff command.
1599 * @return String: unified diff of $before and $after
1601 function wfDiff( $before, $after, $params = '-u' ) {
1602 if ( $before == $after ) {
1607 wfSuppressWarnings();
1608 $haveDiff = $wgDiff && file_exists( $wgDiff );
1609 wfRestoreWarnings();
1611 # This check may also protect against code injection in
1612 # case of broken installations.
1614 wfDebug( "diff executable not found\n" );
1615 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1616 $format = new UnifiedDiffFormatter();
1617 return $format->format( $diffs );
1620 # Make temporary files
1622 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1623 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1625 fwrite( $oldtextFile, $before );
1626 fclose( $oldtextFile );
1627 fwrite( $newtextFile, $after );
1628 fclose( $newtextFile );
1630 // Get the diff of the two files
1631 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1633 $h = popen( $cmd, 'r' );
1638 $data = fread( $h, 8192 );
1639 if ( strlen( $data ) == 0 ) {
1647 unlink( $oldtextName );
1648 unlink( $newtextName );
1650 // Kill the --- and +++ lines. They're not useful.
1651 $diff_lines = explode( "\n", $diff );
1652 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1653 unset( $diff_lines[0] );
1655 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1656 unset( $diff_lines[1] );
1659 $diff = implode( "\n", $diff_lines );
1665 * A wrapper around the PHP function var_export().
1666 * Either print it or add it to the regular output ($wgOut).
1668 * @param $var A PHP variable to dump.
1670 function wfVarDump( $var ) {
1672 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1673 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1676 $wgOut->addHTML( $s );
1681 * Provide a simple HTTP error.
1683 function wfHttpError( $code, $label, $desc ) {
1686 header( "HTTP/1.0 $code $label" );
1687 header( "Status: $code $label" );
1688 $wgOut->sendCacheControl();
1690 header( 'Content-type: text/html; charset=utf-8' );
1691 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1692 '<html><head><title>' .
1693 htmlspecialchars( $label ) .
1694 '</title></head><body><h1>' .
1695 htmlspecialchars( $label ) .
1697 nl2br( htmlspecialchars( $desc ) ) .
1698 "</p></body></html>\n";
1702 * Clear away any user-level output buffers, discarding contents.
1704 * Suitable for 'starting afresh', for instance when streaming
1705 * relatively large amounts of data without buffering, or wanting to
1706 * output image files without ob_gzhandler's compression.
1708 * The optional $resetGzipEncoding parameter controls suppression of
1709 * the Content-Encoding header sent by ob_gzhandler; by default it
1710 * is left. See comments for wfClearOutputBuffers() for why it would
1713 * Note that some PHP configuration options may add output buffer
1714 * layers which cannot be removed; these are left in place.
1716 * @param $resetGzipEncoding Bool
1718 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1719 if( $resetGzipEncoding ) {
1720 // Suppress Content-Encoding and Content-Length
1721 // headers from 1.10+s wfOutputHandler
1722 global $wgDisableOutputCompression;
1723 $wgDisableOutputCompression = true;
1725 while( $status = ob_get_status() ) {
1726 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1727 // Probably from zlib.output_compression or other
1728 // PHP-internal setting which can't be removed.
1730 // Give up, and hope the result doesn't break
1734 if( !ob_end_clean() ) {
1735 // Could not remove output buffer handler; abort now
1736 // to avoid getting in some kind of infinite loop.
1739 if( $resetGzipEncoding ) {
1740 if( $status['name'] == 'ob_gzhandler' ) {
1741 // Reset the 'Content-Encoding' field set by this handler
1742 // so we can start fresh.
1743 header( 'Content-Encoding:' );
1751 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1753 * Clear away output buffers, but keep the Content-Encoding header
1754 * produced by ob_gzhandler, if any.
1756 * This should be used for HTTP 304 responses, where you need to
1757 * preserve the Content-Encoding header of the real result, but
1758 * also need to suppress the output of ob_gzhandler to keep to spec
1759 * and avoid breaking Firefox in rare cases where the headers and
1760 * body are broken over two packets.
1762 function wfClearOutputBuffers() {
1763 wfResetOutputBuffers( false );
1767 * Converts an Accept-* header into an array mapping string values to quality
1770 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1771 # No arg means accept anything (per HTTP spec)
1773 return array( $def => 1.0 );
1778 $parts = explode( ',', $accept );
1780 foreach( $parts as $part ) {
1781 # FIXME: doesn't deal with params like 'text/html; level=1'
1782 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1784 if( !isset( $qpart ) ) {
1785 $prefs[$value] = 1.0;
1786 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1787 $prefs[$value] = floatval( $match[1] );
1795 * Checks if a given MIME type matches any of the keys in the given
1796 * array. Basic wildcards are accepted in the array keys.
1798 * Returns the matching MIME type (or wildcard) if a match, otherwise
1801 * @param $type String
1802 * @param $avail Array
1806 function mimeTypeMatch( $type, $avail ) {
1807 if( array_key_exists( $type, $avail ) ) {
1810 $parts = explode( '/', $type );
1811 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1812 return $parts[0] . '/*';
1813 } elseif( array_key_exists( '*/*', $avail ) ) {
1822 * Returns the 'best' match between a client's requested internet media types
1823 * and the server's list of available types. Each list should be an associative
1824 * array of type to preference (preference is a float between 0.0 and 1.0).
1825 * Wildcards in the types are acceptable.
1827 * @param $cprefs Array: client's acceptable type list
1828 * @param $sprefs Array: server's offered types
1831 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1832 * XXX: generalize to negotiate other stuff
1834 function wfNegotiateType( $cprefs, $sprefs ) {
1837 foreach( array_keys($sprefs) as $type ) {
1838 $parts = explode( '/', $type );
1839 if( $parts[1] != '*' ) {
1840 $ckey = mimeTypeMatch( $type, $cprefs );
1842 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1847 foreach( array_keys( $cprefs ) as $type ) {
1848 $parts = explode( '/', $type );
1849 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1850 $skey = mimeTypeMatch( $type, $sprefs );
1852 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1860 foreach( array_keys( $combine ) as $type ) {
1861 if( $combine[$type] > $bestq ) {
1863 $bestq = $combine[$type];
1872 * Returns an array where the values in the first array are replaced by the
1873 * values in the second array with the corresponding keys
1877 function wfArrayLookup( $a, $b ) {
1878 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1882 * Convenience function; returns MediaWiki timestamp for the present time.
1885 function wfTimestampNow() {
1887 return wfTimestamp( TS_MW
, time() );
1891 * Reference-counted warning suppression
1893 function wfSuppressWarnings( $end = false ) {
1894 static $suppressCount = 0;
1895 static $originalLevel = false;
1898 if ( $suppressCount ) {
1900 if ( !$suppressCount ) {
1901 error_reporting( $originalLevel );
1905 if ( !$suppressCount ) {
1906 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1913 * Restore error level to previous value
1915 function wfRestoreWarnings() {
1916 wfSuppressWarnings( true );
1919 # Autodetect, convert and provide timestamps of various types
1922 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1924 define( 'TS_UNIX', 0 );
1927 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1929 define( 'TS_MW', 1 );
1932 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1934 define( 'TS_DB', 2 );
1937 * RFC 2822 format, for E-mail and HTTP headers
1939 define( 'TS_RFC2822', 3 );
1942 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1944 * This is used by Special:Export
1946 define( 'TS_ISO_8601', 4 );
1949 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1951 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1952 * DateTime tag and page 36 for the DateTimeOriginal and
1953 * DateTimeDigitized tags.
1955 define( 'TS_EXIF', 5 );
1958 * Oracle format time.
1960 define( 'TS_ORACLE', 6 );
1963 * Postgres format time.
1965 define( 'TS_POSTGRES', 7 );
1970 define( 'TS_DB2', 8 );
1973 * ISO 8601 basic format with no timezone: 19860209T200000Z
1975 * This is used by ResourceLoader
1977 define( 'TS_ISO_8601_BASIC', 9 );
1980 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1981 * function will autodetect which format is supplied and act
1983 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1984 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1986 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1993 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1995 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1997 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1999 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2002 $strtime = "@$ts"; // Undocumented?
2003 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2004 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2005 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2006 str_replace( '+00:00', 'UTC', $ts ) );
2007 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2009 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2011 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2013 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2015 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2017 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2018 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2019 '[ \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
2020 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2021 # The regex is a superset of rfc2822 for readability
2022 $strtime = strtok( $ts, ';' );
2023 } 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 ) ) {
2026 } 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 ) ) {
2030 # Bogus value; fall back to the epoch...
2031 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2038 static $formats = array(
2041 TS_DB
=> 'Y-m-d H:i:s',
2042 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2043 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2044 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2045 TS_RFC2822
=> 'D, d M Y H:i:s',
2046 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2047 TS_POSTGRES
=> 'Y-m-d H:i:s',
2048 TS_DB2
=> 'Y-m-d H:i:s',
2051 if ( !isset( $formats[$outputtype] ) ) {
2052 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2055 if ( function_exists( "date_create" ) ) {
2056 if ( count( $da ) ) {
2057 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2058 (int)$da[1], (int)$da[2], (int)$da[3],
2059 (int)$da[4], (int)$da[5], (int)$da[6]);
2061 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2062 } elseif ( $strtime ) {
2063 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2069 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2073 $output = $d->format( $formats[$outputtype] );
2075 if ( count( $da ) ) {
2076 // Warning! gmmktime() acts oddly if the month or day is set to 0
2077 // We may want to handle that explicitly at some point
2078 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2079 (int)$da[2], (int)$da[3], (int)$da[1] );
2080 } elseif ( $strtime ) {
2081 $uts = strtotime( $strtime );
2084 if ( $uts === false ) {
2085 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2089 if ( TS_UNIX
== $outputtype ) {
2092 $output = gmdate( $formats[$outputtype], $uts );
2095 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2103 * Return a formatted timestamp, or null if input is null.
2104 * For dealing with nullable timestamp columns in the database.
2105 * @param $outputtype Integer
2109 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2110 if( is_null( $ts ) ) {
2113 return wfTimestamp( $outputtype, $ts );
2118 * Check if the operating system is Windows
2120 * @return Bool: true if it's Windows, False otherwise.
2122 function wfIsWindows() {
2123 static $isWindows = null;
2124 if ( $isWindows === null ) {
2125 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2131 * Swap two variables
2133 function swap( &$x, &$y ) {
2139 function wfGetCachedNotice( $name ) {
2140 global $wgOut, $wgRenderHashAppend, $parserMemc;
2141 $fname = 'wfGetCachedNotice';
2142 wfProfileIn( $fname );
2146 if( $name === 'default' ) {
2148 global $wgSiteNotice;
2149 $notice = $wgSiteNotice;
2150 if( empty( $notice ) ) {
2151 wfProfileOut( $fname );
2155 $notice = wfMsgForContentNoTrans( $name );
2156 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2157 wfProfileOut( $fname );
2162 // Use the extra hash appender to let eg SSL variants separately cache.
2163 $key = wfMemcKey( $name . $wgRenderHashAppend );
2164 $cachedNotice = $parserMemc->get( $key );
2165 if( is_array( $cachedNotice ) ) {
2166 if( md5( $notice ) == $cachedNotice['hash'] ) {
2167 $notice = $cachedNotice['html'];
2176 if( is_object( $wgOut ) ) {
2177 $parsed = $wgOut->parse( $notice );
2178 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2181 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2185 $notice = '<div id="localNotice">' .$notice . '</div>';
2186 wfProfileOut( $fname );
2190 function wfGetNamespaceNotice() {
2194 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2198 $fname = 'wfGetNamespaceNotice';
2199 wfProfileIn( $fname );
2201 $key = 'namespacenotice-' . $wgTitle->getNsText();
2202 $namespaceNotice = wfGetCachedNotice( $key );
2203 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2204 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2206 $namespaceNotice = '';
2209 wfProfileOut( $fname );
2210 return $namespaceNotice;
2213 function wfGetSiteNotice() {
2215 $fname = 'wfGetSiteNotice';
2216 wfProfileIn( $fname );
2219 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2220 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2221 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2223 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2224 if( !$anonNotice ) {
2225 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2227 $siteNotice = $anonNotice;
2230 if( !$siteNotice ) {
2231 $siteNotice = wfGetCachedNotice( 'default' );
2235 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2236 wfProfileOut( $fname );
2241 * BC wrapper for MimeMagic::singleton()
2242 * @deprecated No longer needed as of 1.17 (r68836).
2244 function &wfGetMimeMagic() {
2245 wfDeprecated( __FUNCTION__
);
2246 return MimeMagic
::singleton();
2250 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2251 * TEMP environment variables are then checked in sequence, and if none are set
2252 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2253 * or C:\Windows\Temp for Windows and hope for the best.
2254 * It is common to call it with tempnam().
2256 * NOTE: When possible, use instead the tmpfile() function to create
2257 * temporary files to avoid race conditions on file creation, etc.
2261 function wfTempDir() {
2262 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2263 $tmp = getenv( $var );
2264 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2268 if( function_exists( 'sys_get_temp_dir' ) ) {
2269 return sys_get_temp_dir();
2272 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2276 * Make directory, and make all parent directories if they don't exist
2278 * @param $dir String: full path to directory to create
2279 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2280 * @param $caller String: optional caller param for debugging.
2283 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2284 global $wgDirectoryMode;
2286 if ( !is_null( $caller ) ) {
2287 wfDebug( "$caller: called wfMkdirParents($dir)" );
2290 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2294 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2296 if ( is_null( $mode ) ) {
2297 $mode = $wgDirectoryMode;
2300 // Turn off the normal warning, we're doing our own below
2301 wfSuppressWarnings();
2302 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2303 wfRestoreWarnings();
2306 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2307 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2313 * Increment a statistics counter
2315 function wfIncrStats( $key ) {
2316 global $wgStatsMethod;
2318 if( $wgStatsMethod == 'udp' ) {
2319 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2322 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2323 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2327 strlen( $statline ),
2333 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2334 wfSuppressWarnings();
2338 strlen( $statline ),
2343 wfRestoreWarnings();
2344 } elseif( $wgStatsMethod == 'cache' ) {
2346 $key = wfMemcKey( 'stats', $key );
2347 if ( is_null( $wgMemc->incr( $key ) ) ) {
2348 $wgMemc->add( $key, 1 );
2356 * @param $nr Mixed: the number to format
2357 * @param $acc Integer: the number of digits after the decimal point, default 2
2358 * @param $round Boolean: whether or not to round the value, default true
2361 function wfPercent( $nr, $acc = 2, $round = true ) {
2362 $ret = sprintf( "%.${acc}f", $nr );
2363 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2367 * Encrypt a username/password.
2369 * @param $userid Integer: ID of the user
2370 * @param $password String: password of the user
2371 * @return String: hashed password
2372 * @deprecated Use User::crypt() or User::oldCrypt() instead
2374 function wfEncryptPassword( $userid, $password ) {
2375 wfDeprecated(__FUNCTION__
);
2376 # Just wrap around User::oldCrypt()
2377 return User
::oldCrypt( $password, $userid );
2381 * Appends to second array if $value differs from that in $default
2383 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2384 if ( is_null( $changed ) ) {
2385 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2387 if ( $default[$key] !== $value ) {
2388 $changed[$key] = $value;
2393 * Since wfMsg() and co suck, they don't return false if the message key they
2394 * looked up didn't exist but a XHTML string, this function checks for the
2395 * nonexistance of messages by looking at wfMsg() output
2397 * @param $key String: the message key looked up
2398 * @return Boolean True if the message *doesn't* exist.
2400 function wfEmptyMsg( $key ) {
2401 global $wgMessageCache;
2402 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2406 * Find out whether or not a mixed variable exists in a string
2408 * @param $needle String
2409 * @param $str String
2412 function in_string( $needle, $str ) {
2413 return strpos( $str, $needle ) !== false;
2416 function wfSpecialList( $page, $details ) {
2418 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2419 return $page . $details;
2423 * Returns a regular expression of url protocols
2427 function wfUrlProtocols() {
2428 global $wgUrlProtocols;
2430 static $retval = null;
2431 if ( !is_null( $retval ) ) {
2435 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2436 // with LocalSettings files from 1.5
2437 if ( is_array( $wgUrlProtocols ) ) {
2438 $protocols = array();
2439 foreach ( $wgUrlProtocols as $protocol ) {
2440 $protocols[] = preg_quote( $protocol, '/' );
2443 $retval = implode( '|', $protocols );
2445 $retval = $wgUrlProtocols;
2451 * Safety wrapper around ini_get() for boolean settings.
2452 * The values returned from ini_get() are pre-normalized for settings
2453 * set via php.ini or php_flag/php_admin_flag... but *not*
2454 * for those set via php_value/php_admin_value.
2456 * It's fairly common for people to use php_value instead of php_flag,
2457 * which can leave you with an 'off' setting giving a false positive
2458 * for code that just takes the ini_get() return value as a boolean.
2460 * To make things extra interesting, setting via php_value accepts
2461 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2462 * Unrecognized values go false... again opposite PHP's own coercion
2463 * from string to bool.
2465 * Luckily, 'properly' set settings will always come back as '0' or '1',
2466 * so we only have to worry about them and the 'improper' settings.
2468 * I frickin' hate PHP... :P
2470 * @param $setting String
2473 function wfIniGetBool( $setting ) {
2474 $val = ini_get( $setting );
2475 // 'on' and 'true' can't have whitespace around them, but '1' can.
2476 return strtolower( $val ) == 'on'
2477 ||
strtolower( $val ) == 'true'
2478 ||
strtolower( $val ) == 'yes'
2479 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2483 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2484 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2486 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2488 * @return Bool - Whether or not the extension is loaded
2490 function wfDl( $extension ) {
2491 if( extension_loaded( $extension ) ) {
2495 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2496 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2499 wfSuppressWarnings();
2500 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2501 wfRestoreWarnings();
2503 return extension_loaded( $extension );
2507 * Execute a shell command, with time and memory limits mirrored from the PHP
2508 * configuration if supported.
2509 * @param $cmd String Command line, properly escaped for shell.
2510 * @param &$retval optional, will receive the program's exit code.
2511 * (non-zero is usually failure)
2512 * @param $environ Array optional environment variables which should be
2513 * added to the executed command environment.
2514 * @return collected stdout as a string (trailing newlines stripped)
2516 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2517 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2520 if ( is_null( $disabled ) ) {
2522 if( wfIniGetBool( 'safe_mode' ) ) {
2523 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2524 $disabled = 'safemode';
2526 $functions = explode( ',', ini_get( 'disable_functions' ) );
2527 $functions = array_map( 'trim', $functions );
2528 $functions = array_map( 'strtolower', $functions );
2529 if ( in_array( 'passthru', $functions ) ) {
2530 wfDebug( "passthru is in disabled_functions\n" );
2531 $disabled = 'passthru';
2537 return $disabled == 'safemode' ?
2538 'Unable to run external programs in safe mode.' :
2539 'Unable to run external programs, passthru() is disabled.';
2542 wfInitShellLocale();
2545 foreach( $environ as $k => $v ) {
2546 if ( wfIsWindows() ) {
2547 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2548 * appear in the environment variable, so we must use carat escaping as documented in
2549 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2550 * Note however that the quote isn't listed there, but is needed, and the parentheses
2551 * are listed there but doesn't appear to need it.
2553 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . ' && ';
2555 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2556 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2558 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2561 $cmd = $envcmd . $cmd;
2563 if ( wfIsWindows() ) {
2564 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2565 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2567 # Hack to work around PHP's flawed invocation of cmd.exe
2568 # http://news.php.net/php.internals/21796
2569 # Windows 9x doesn't accept any kind of quotes
2570 $cmd = '"' . $cmd . '"';
2572 } elseif ( php_uname( 's' ) == 'Linux' ) {
2573 $time = intval( $wgMaxShellTime );
2574 $mem = intval( $wgMaxShellMemory );
2575 $filesize = intval( $wgMaxShellFileSize );
2577 if ( $time > 0 && $mem > 0 ) {
2578 $script = "$IP/bin/ulimit4.sh";
2579 if ( is_executable( $script ) ) {
2580 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2584 wfDebug( "wfShellExec: $cmd\n" );
2586 $retval = 1; // error by default?
2588 passthru( $cmd, $retval );
2589 $output = ob_get_contents();
2592 if ( $retval == 127 ) {
2593 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2599 * Workaround for http://bugs.php.net/bug.php?id=45132
2600 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2602 function wfInitShellLocale() {
2603 static $done = false;
2608 global $wgShellLocale;
2609 if ( !wfIniGetBool( 'safe_mode' ) ) {
2610 putenv( "LC_CTYPE=$wgShellLocale" );
2611 setlocale( LC_CTYPE
, $wgShellLocale );
2616 * This function works like "use VERSION" in Perl, the program will die with a
2617 * backtrace if the current version of PHP is less than the version provided
2619 * This is useful for extensions which due to their nature are not kept in sync
2620 * with releases, and might depend on other versions of PHP than the main code
2622 * Note: PHP might die due to parsing errors in some cases before it ever
2623 * manages to call this function, such is life
2625 * @see perldoc -f use
2627 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2630 function wfUsePHP( $req_ver ) {
2631 $php_ver = PHP_VERSION
;
2633 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2634 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2639 * This function works like "use VERSION" in Perl except it checks the version
2640 * of MediaWiki, the program will die with a backtrace if the current version
2641 * of MediaWiki is less than the version provided.
2643 * This is useful for extensions which due to their nature are not kept in sync
2646 * @see perldoc -f use
2648 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2651 function wfUseMW( $req_ver ) {
2654 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2655 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2660 * Return the final portion of a pathname.
2661 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2662 * http://bugs.php.net/bug.php?id=33898
2664 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2665 * We'll consider it so always, as we don't want \s in our Unix paths either.
2667 * @param $path String
2668 * @param $suffix String: to remove if present
2671 function wfBaseName( $path, $suffix = '' ) {
2672 $encSuffix = ( $suffix == '' )
2674 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2676 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2684 * Generate a relative path name to the given file.
2685 * May explode on non-matching case-insensitive paths,
2686 * funky symlinks, etc.
2688 * @param $path String: absolute destination path including target filename
2689 * @param $from String: Absolute source path, directory only
2692 function wfRelativePath( $path, $from ) {
2693 // Normalize mixed input on Windows...
2694 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2695 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2697 // Trim trailing slashes -- fix for drive root
2698 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2699 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2701 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2702 $against = explode( DIRECTORY_SEPARATOR
, $from );
2704 if( $pieces[0] !== $against[0] ) {
2705 // Non-matching Windows drive letters?
2706 // Return a full path.
2710 // Trim off common prefix
2711 while( count( $pieces ) && count( $against )
2712 && $pieces[0] == $against[0] ) {
2713 array_shift( $pieces );
2714 array_shift( $against );
2717 // relative dots to bump us to the parent
2718 while( count( $against ) ) {
2719 array_unshift( $pieces, '..' );
2720 array_shift( $against );
2723 array_push( $pieces, wfBaseName( $path ) );
2725 return implode( DIRECTORY_SEPARATOR
, $pieces );
2729 * Backwards array plus for people who haven't bothered to read the PHP manual
2730 * XXX: will not darn your socks for you.
2732 * @param $array1 Array
2733 * @param [$array2, [...]] Arrays
2736 function wfArrayMerge( $array1/* ... */ ) {
2737 $args = func_get_args();
2738 $args = array_reverse( $args, true );
2740 foreach ( $args as $arg ) {
2747 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2749 * wfMergeErrorArrays(
2750 * array( array( 'x' ) ),
2751 * array( array( 'x', '2' ) ),
2752 * array( array( 'x' ) ),
2753 * array( array( 'y') )
2757 * array( 'x', '2' ),
2762 function wfMergeErrorArrays( /*...*/ ) {
2763 $args = func_get_args();
2765 foreach ( $args as $errors ) {
2766 foreach ( $errors as $params ) {
2767 # FIXME: sometimes get nested arrays for $params,
2768 # which leads to E_NOTICEs
2769 $spec = implode( "\t", $params );
2770 $out[$spec] = $params;
2773 return array_values( $out );
2777 * parse_url() work-alike, but non-broken. Differences:
2779 * 1) Does not raise warnings on bad URLs (just returns false)
2780 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2781 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2783 * @param $url String: a URL to parse
2784 * @return Array: bits of the URL in an associative array, per PHP docs
2786 function wfParseUrl( $url ) {
2787 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2788 wfSuppressWarnings();
2789 $bits = parse_url( $url );
2790 wfRestoreWarnings();
2795 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2796 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2797 $bits['delimiter'] = '://';
2798 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2799 $bits['delimiter'] = ':';
2800 // parse_url detects for news: and mailto: the host part of an url as path
2801 // We have to correct this wrong detection
2802 if ( isset( $bits['path'] ) ) {
2803 $bits['host'] = $bits['path'];
2814 * Make a URL index, appropriate for the el_index field of externallinks.
2816 function wfMakeUrlIndex( $url ) {
2817 $bits = wfParseUrl( $url );
2819 // Reverse the labels in the hostname, convert to lower case
2820 // For emails reverse domainpart only
2821 if ( $bits['scheme'] == 'mailto' ) {
2822 $mailparts = explode( '@', $bits['host'], 2 );
2823 if ( count( $mailparts ) === 2 ) {
2824 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2826 // No domain specified, don't mangle it
2829 $reversedHost = $domainpart . '@' . $mailparts[0];
2831 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2833 // Add an extra dot to the end
2834 // Why? Is it in wrong place in mailto links?
2835 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2836 $reversedHost .= '.';
2838 // Reconstruct the pseudo-URL
2839 $prot = $bits['scheme'];
2840 $index = $prot . $bits['delimiter'] . $reversedHost;
2841 // Leave out user and password. Add the port, path, query and fragment
2842 if ( isset( $bits['port'] ) ) {
2843 $index .= ':' . $bits['port'];
2845 if ( isset( $bits['path'] ) ) {
2846 $index .= $bits['path'];
2850 if ( isset( $bits['query'] ) ) {
2851 $index .= '?' . $bits['query'];
2853 if ( isset( $bits['fragment'] ) ) {
2854 $index .= '#' . $bits['fragment'];
2860 * Do any deferred updates and clear the list
2861 * TODO: This could be in Wiki.php if that class made any sense at all
2863 function wfDoUpdates() {
2864 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2865 foreach ( $wgDeferredUpdateList as $update ) {
2866 $update->doUpdate();
2868 foreach ( $wgPostCommitUpdateList as $update ) {
2869 $update->doUpdate();
2871 $wgDeferredUpdateList = array();
2872 $wgPostCommitUpdateList = array();
2876 * Convert an arbitrarily-long digit string from one numeric base
2877 * to another, optionally zero-padding to a minimum column width.
2879 * Supports base 2 through 36; digit values 10-36 are represented
2880 * as lowercase letters a-z. Input is case-insensitive.
2882 * @param $input String: of digits
2883 * @param $sourceBase Integer: 2-36
2884 * @param $destBase Integer: 2-36
2885 * @param $pad Integer: 1 or greater
2886 * @param $lowercase Boolean
2887 * @return String or false on invalid input
2889 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2890 $input = strval( $input );
2891 if( $sourceBase < 2 ||
2896 $sourceBase != intval( $sourceBase ) ||
2897 $destBase != intval( $destBase ) ||
2898 $pad != intval( $pad ) ||
2899 !is_string( $input ) ||
2903 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2904 $inDigits = array();
2907 // Decode and validate input string
2908 $input = strtolower( $input );
2909 for( $i = 0; $i < strlen( $input ); $i++
) {
2910 $n = strpos( $digitChars, $input{$i} );
2911 if( $n === false ||
$n > $sourceBase ) {
2917 // Iterate over the input, modulo-ing out an output digit
2918 // at a time until input is gone.
2919 while( count( $inDigits ) ) {
2921 $workDigits = array();
2924 foreach( $inDigits as $digit ) {
2925 $work *= $sourceBase;
2928 if( $work < $destBase ) {
2929 // Gonna need to pull another digit.
2930 if( count( $workDigits ) ) {
2931 // Avoid zero-padding; this lets us find
2932 // the end of the input very easily when
2933 // length drops to zero.
2937 // Finally! Actual division!
2938 $workDigits[] = intval( $work / $destBase );
2940 // Isn't it annoying that most programming languages
2941 // don't have a single divide-and-remainder operator,
2942 // even though the CPU implements it that way?
2943 $work = $work %
$destBase;
2947 // All that division leaves us with a remainder,
2948 // which is conveniently our next output digit.
2949 $outChars .= $digitChars[$work];
2952 $inDigits = $workDigits;
2955 while( strlen( $outChars ) < $pad ) {
2959 return strrev( $outChars );
2963 * Create an object with a given name and an array of construct parameters
2964 * @param $name String
2965 * @param $p Array: parameters
2967 function wfCreateObject( $name, $p ) {
2968 $p = array_values( $p );
2969 switch ( count( $p ) ) {
2973 return new $name( $p[0] );
2975 return new $name( $p[0], $p[1] );
2977 return new $name( $p[0], $p[1], $p[2] );
2979 return new $name( $p[0], $p[1], $p[2], $p[3] );
2981 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2983 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2985 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2989 function wfHttpOnlySafe() {
2990 global $wgHttpOnlyBlacklist;
2991 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
2995 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2996 foreach( $wgHttpOnlyBlacklist as $regex ) {
2997 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3007 * Initialise php session
3009 function wfSetupSession( $sessionId = false ) {
3010 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3011 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3012 if( $wgSessionsInMemcached ) {
3013 require_once( 'MemcachedSessions.php' );
3014 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3015 # Only set this if $wgSessionHandler isn't null and session.save_handler
3016 # hasn't already been set to the desired value (that causes errors)
3017 ini_set( 'session.save_handler', $wgSessionHandler );
3019 $httpOnlySafe = wfHttpOnlySafe();
3020 wfDebugLog( 'cookie',
3021 'session_set_cookie_params: "' . implode( '", "',
3027 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3028 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3029 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3031 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3032 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3034 session_cache_limiter( 'private, must-revalidate' );
3036 session_id( $sessionId );
3038 wfSuppressWarnings();
3040 wfRestoreWarnings();
3044 * Get an object from the precompiled serialized directory
3046 * @return Mixed: the variable on success, false on failure
3048 function wfGetPrecompiledData( $name ) {
3051 $file = "$IP/serialized/$name";
3052 if ( file_exists( $file ) ) {
3053 $blob = file_get_contents( $file );
3055 return unserialize( $blob );
3061 function wfGetCaller( $level = 2 ) {
3062 $backtrace = wfDebugBacktrace();
3063 if ( isset( $backtrace[$level] ) ) {
3064 return wfFormatStackFrame( $backtrace[$level] );
3066 $caller = 'unknown';
3072 * Return a string consisting of callers in the stack. Useful sometimes
3073 * for profiling specific points.
3075 * @param $limit The maximum depth of the stack frame to return, or false for
3078 function wfGetAllCallers( $limit = 3 ) {
3079 $trace = array_reverse( wfDebugBacktrace() );
3080 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3081 $limit = count( $trace ) - 1;
3083 $trace = array_slice( $trace, -$limit - 1, $limit );
3084 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3088 * Return a string representation of frame
3090 function wfFormatStackFrame( $frame ) {
3091 return isset( $frame['class'] ) ?
3092 $frame['class'] . '::' . $frame['function'] :
3099 function wfMemcKey( /*... */ ) {
3100 $args = func_get_args();
3101 $key = wfWikiID() . ':' . implode( ':', $args );
3102 $key = str_replace( ' ', '_', $key );
3107 * Get a cache key for a foreign DB
3109 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3110 $args = array_slice( func_get_args(), 2 );
3112 $key = "$db-$prefix:" . implode( ':', $args );
3114 $key = $db . ':' . implode( ':', $args );
3120 * Get an ASCII string identifying this wiki
3121 * This is used as a prefix in memcached keys
3123 function wfWikiID() {
3124 global $wgDBprefix, $wgDBname;
3125 if ( $wgDBprefix ) {
3126 return "$wgDBname-$wgDBprefix";
3133 * Split a wiki ID into DB name and table prefix
3135 function wfSplitWikiID( $wiki ) {
3136 $bits = explode( '-', $wiki, 2 );
3137 if ( count( $bits ) < 2 ) {
3144 * Get a Database object.
3145 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3146 * master (for write queries), DB_SLAVE for potentially lagged read
3147 * queries, or an integer >= 0 for a particular server.
3149 * @param $groups Mixed: query groups. An array of group names that this query
3150 * belongs to. May contain a single string if the query is only
3153 * @param $wiki String: the wiki ID, or false for the current wiki
3155 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3156 * will always return the same object, unless the underlying connection or load
3157 * balancer is manually destroyed.
3159 * @return DatabaseBase
3161 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3162 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3166 * Get a load balancer object.
3168 * @param $wiki String: wiki ID, or false for the current wiki
3169 * @return LoadBalancer
3171 function wfGetLB( $wiki = false ) {
3172 return wfGetLBFactory()->getMainLB( $wiki );
3176 * Get the load balancer factory object
3178 function &wfGetLBFactory() {
3179 return LBFactory
::singleton();
3184 * Shortcut for RepoGroup::singleton()->findFile()
3185 * @param $title String or Title object
3186 * @param $options Associative array of options:
3187 * time: requested time for an archived image, or false for the
3188 * current version. An image object will be returned which was
3189 * created at the specified time.
3191 * ignoreRedirect: If true, do not follow file redirects
3193 * private: If true, return restricted (deleted) files if the current
3194 * user is allowed to view them. Otherwise, such files will not
3197 * bypassCache: If true, do not use the process-local cache of File objects
3199 * @return File, or false if the file does not exist
3201 function wfFindFile( $title, $options = array() ) {
3202 return RepoGroup
::singleton()->findFile( $title, $options );
3206 * Get an object referring to a locally registered file.
3207 * Returns a valid placeholder object if the file does not exist.
3208 * @param $title Either a string or Title object
3209 * @return File, or null if passed an invalid Title
3211 function wfLocalFile( $title ) {
3212 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3216 * Should low-performance queries be disabled?
3220 function wfQueriesMustScale() {
3221 global $wgMiserMode;
3223 ||
( SiteStats
::pages() > 100000
3224 && SiteStats
::edits() > 1000000
3225 && SiteStats
::users() > 10000 );
3229 * Get the path to a specified script file, respecting file
3230 * extensions; this is a wrapper around $wgScriptExtension etc.
3232 * @param $script String: script filename, sans extension
3235 function wfScript( $script = 'index' ) {
3236 global $wgScriptPath, $wgScriptExtension;
3237 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3241 * Get the script URL.
3243 * @return script URL
3245 function wfGetScriptUrl() {
3246 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3248 # as it was called, minus the query string.
3250 # Some sites use Apache rewrite rules to handle subdomains,
3251 # and have PHP set up in a weird way that causes PHP_SELF
3252 # to contain the rewritten URL instead of the one that the
3253 # outside world sees.
3255 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3256 # provides containing the "before" URL.
3257 return $_SERVER['SCRIPT_NAME'];
3259 return $_SERVER['URL'];
3264 * Convenience function converts boolean values into "true"
3265 * or "false" (string) values
3267 * @param $value Boolean
3270 function wfBoolToStr( $value ) {
3271 return $value ?
'true' : 'false';
3275 * Load an extension messages file
3276 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3278 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3282 * Get a platform-independent path to the null file, e.g.
3287 function wfGetNull() {
3288 return wfIsWindows()
3294 * Displays a maxlag error
3296 * @param $host String: server that lags the most
3297 * @param $lag Integer: maxlag (actual)
3298 * @param $maxLag Integer: maxlag (requested)
3300 function wfMaxlagError( $host, $lag, $maxLag ) {
3301 global $wgShowHostnames;
3302 header( 'HTTP/1.1 503 Service Unavailable' );
3303 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3304 header( 'X-Database-Lag: ' . intval( $lag ) );
3305 header( 'Content-Type: text/plain' );
3306 if( $wgShowHostnames ) {
3307 echo "Waiting for $host: $lag seconds lagged\n";
3309 echo "Waiting for a database server: $lag seconds lagged\n";
3314 * Throws a warning that $function is deprecated
3315 * @param $function String
3318 function wfDeprecated( $function ) {
3319 static $functionsWarned = array();
3320 if ( !isset( $functionsWarned[$function] ) ) {
3321 $functionsWarned[$function] = true;
3322 wfWarn( "Use of $function is deprecated.", 2 );
3327 * Send a warning either to the debug log or in a PHP error depending on
3328 * $wgDevelopmentWarnings
3330 * @param $msg String: message to send
3331 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3332 * find the correct caller (1 = function calling wfWarn, ...)
3333 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3336 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3337 $callers = wfDebugBacktrace();
3338 if( isset( $callers[$callerOffset +
1] ) ){
3339 $callerfunc = $callers[$callerOffset +
1];
3340 $callerfile = $callers[$callerOffset];
3341 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3342 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3344 $file = '(internal function)';
3347 if( isset( $callerfunc['class'] ) ) {
3348 $func .= $callerfunc['class'] . '::';
3350 if( isset( $callerfunc['function'] ) ) {
3351 $func .= $callerfunc['function'];
3353 $msg .= " [Called from $func in $file]";
3356 global $wgDevelopmentWarnings;
3357 if ( $wgDevelopmentWarnings ) {
3358 trigger_error( $msg, $level );
3360 wfDebug( "$msg\n" );
3365 * Sleep until the worst slave's replication lag is less than or equal to
3366 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3367 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3368 * a no-op if there are no slaves.
3370 * Every time the function has to wait for a slave, it will print a message to
3371 * that effect (and then sleep for a little while), so it's probably not best
3372 * to use this outside maintenance scripts in its present form.
3374 * @param $maxLag Integer
3375 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3378 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3380 $lb = wfGetLB( $wiki );
3381 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3382 while( $lag > $maxLag ) {
3383 wfSuppressWarnings();
3384 $name = gethostbyaddr( $host );
3385 wfRestoreWarnings();
3386 if( $name !== false ) {
3389 print "Waiting for $host (lagged $lag seconds)...\n";
3391 list( $host, $lag ) = $lb->getMaxLag();
3397 * Output some plain text in command-line mode or in the installer (updaters.inc).
3398 * Do not use it in any other context, its behaviour is subject to change.
3400 function wfOut( $s ) {
3401 global $wgCommandLineMode;
3402 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3405 echo htmlspecialchars( $s );
3411 * Count down from $n to zero on the terminal, with a one-second pause
3412 * between showing each number. For use in command-line scripts.
3414 function wfCountDown( $n ) {
3415 for ( $i = $n; $i >= 0; $i-- ) {
3417 echo str_repeat( "\x08", strlen( $i +
1 ) );
3429 * Generate a random 32-character hexadecimal token.
3430 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3431 * characters before hashing.
3433 function wfGenerateToken( $salt = '' ) {
3434 $salt = serialize( $salt );
3435 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3439 * Replace all invalid characters with -
3440 * @param $name Mixed: filename to process
3442 function wfStripIllegalFilenameChars( $name ) {
3443 global $wgIllegalFileChars;
3444 $name = wfBaseName( $name );
3445 $name = preg_replace(
3446 "/[^" . Title
::legalChars() . "]" .
3447 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3456 * Insert array into another array after the specified *KEY*
3457 * @param $array Array: The array.
3458 * @param $insert Array: The array to insert.
3459 * @param $after Mixed: The key to insert after
3461 function wfArrayInsertAfter( $array, $insert, $after ) {
3462 // Find the offset of the element to insert after.
3463 $keys = array_keys( $array );
3464 $offsetByKey = array_flip( $keys );
3466 $offset = $offsetByKey[$after];
3468 // Insert at the specified offset
3469 $before = array_slice( $array, 0, $offset +
1, true );
3470 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3472 $output = $before +
$insert +
$after;
3477 /* Recursively converts the parameter (an object) to an array with the same data */
3478 function wfObjectToArray( $object, $recursive = true ) {
3480 foreach ( get_object_vars( $object ) as $key => $value ) {
3481 if ( is_object( $value ) && $recursive ) {
3482 $value = wfObjectToArray( $value );
3485 $array[$key] = $value;
3492 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3493 * @return Integer value memory was set to.
3495 function wfMemoryLimit() {
3496 global $wgMemoryLimit;
3497 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3498 if( $memlimit != -1 ) {
3499 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3500 if( $conflimit == -1 ) {
3501 wfDebug( "Removing PHP's memory limit\n" );
3502 wfSuppressWarnings();
3503 ini_set( 'memory_limit', $conflimit );
3504 wfRestoreWarnings();
3506 } elseif ( $conflimit > $memlimit ) {
3507 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3508 wfSuppressWarnings();
3509 ini_set( 'memory_limit', $conflimit );
3510 wfRestoreWarnings();
3518 * Converts shorthand byte notation to integer form
3519 * @param $string String
3522 function wfShorthandToInteger( $string = '' ) {
3523 $string = trim( $string );
3524 if( $string === '' ) {
3527 $last = $string[strlen( $string ) - 1];
3528 $val = intval( $string );
3533 // break intentionally missing
3537 // break intentionally missing
3547 * Get the normalised IETF language tag
3548 * @param $code String: The language code.
3549 * @return $langCode String: The language code which complying with BCP 47 standards.
3551 function wfBCP47( $code ) {
3552 $codeSegment = explode( '-', $code );
3553 foreach ( $codeSegment as $segNo => $seg ) {
3554 if ( count( $codeSegment ) > 0 ) {
3555 // ISO 3166 country code
3556 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3557 $codeBCP[$segNo] = strtoupper( $seg );
3558 // ISO 15924 script code
3559 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3560 $codeBCP[$segNo] = ucfirst( $seg );
3561 // Use lowercase for other cases
3563 $codeBCP[$segNo] = strtolower( $seg );
3566 // Use lowercase for single segment
3567 $codeBCP[$segNo] = strtolower( $seg );
3570 $langCode = implode( '-', $codeBCP );
3574 function wfArrayMap( $function, $input ) {
3575 $ret = array_map( $function, $input );
3576 foreach ( $ret as $key => $value ) {
3577 $taint = istainted( $input[$key] );
3579 taint( $ret[$key], $taint );
3586 * Returns the PackageRepository object for interaction with the package repository.
3588 * TODO: Make the repository type also configurable.
3592 * @return PackageRepository
3594 function wfGetRepository() {
3595 global $wgRepositoryApiLocation;
3596 static $repository = false;
3598 if ( $repository === false ) {
3599 $repository = new DistributionRepository( $wgRepositoryApiLocation );