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( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
218 $cmp = strcmp( $valueA, $valueB );
228 * Get a random decimal value between 0 and 1, in a way
229 * not likely to give duplicate values for any realistic
230 * number of articles.
234 function wfRandom() {
235 # The maximum random value is "only" 2^31-1, so get two random
236 # values to reduce the chance of dupes
237 $max = mt_getrandmax() +
1;
238 $rand = number_format( ( mt_rand() * $max +
mt_rand() )
239 / $max / $max, 12, '.', '' );
244 * We want some things to be included as literal characters in our title URLs
245 * for prettiness, which urlencode encodes by default. According to RFC 1738,
246 * all of the following should be safe:
250 * But + is not safe because it's used to indicate a space; &= are only safe in
251 * paths and not in queries (and we don't distinguish here); ' seems kind of
252 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
253 * is reserved, we don't care. So the list we unescape is:
257 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
258 * so no fancy : for IIS7.
260 * %2F in the page titles seems to fatally break for some reason.
265 function wfUrlencode( $s ) {
267 if ( is_null( $needle ) ) {
268 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
269 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
274 $s = urlencode( $s );
277 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
285 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
286 * In normal operation this is a NOP.
288 * Controlling globals:
289 * $wgDebugLogFile - points to the log file
290 * $wgProfileOnly - if set, normal debug messages will not be recorded.
291 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
292 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
294 * @param $text String
295 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
297 function wfDebug( $text, $logonly = false ) {
298 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
299 global $wgDebugLogPrefix, $wgShowDebug;
300 static $recursion = 0;
302 static $cache = array(); // Cache of unoutputted messages
303 $text = wfDebugTimer() . $text;
305 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
306 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
310 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
313 if ( !isset( $wgOut ) ) {
316 if ( !StubObject
::isRealObject( $wgOut ) ) {
325 // add the message and possible cached ones to the output
326 array_map( array( $wgOut, 'debug' ), $cache );
329 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
330 # Strip unprintables; they can switch terminal modes when binary data
331 # gets dumped, which is pretty annoying.
332 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
333 $text = $wgDebugLogPrefix . $text;
334 wfErrorLog( $text, $wgDebugLogFile );
338 function wfDebugTimer() {
339 global $wgDebugTimestamps;
340 if ( !$wgDebugTimestamps ) {
343 static $start = null;
345 if ( $start === null ) {
346 $start = microtime( true );
347 $prefix = "\n$start";
349 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
352 return $prefix . ' ';
356 * Send a line giving PHP memory usage.
357 * @param $exact Bool: print exact values instead of kilobytes (default: false)
359 function wfDebugMem( $exact = false ) {
360 $mem = memory_get_usage();
362 $mem = floor( $mem / 1024 ) . ' kilobytes';
366 wfDebug( "Memory usage: $mem\n" );
370 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
371 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
373 * @param $logGroup String
374 * @param $text String
375 * @param $public Bool: whether to log the event in the public log if no private
376 * log file is specified, (default true)
378 function wfDebugLog( $logGroup, $text, $public = true ) {
379 global $wgDebugLogGroups, $wgShowHostnames;
380 $text = trim( $text ) . "\n";
381 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
382 $time = wfTimestamp( TS_DB
);
384 if ( $wgShowHostnames ) {
385 $host = wfHostname();
389 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
390 } elseif ( $public === true ) {
391 wfDebug( $text, true );
396 * Log for database errors
397 * @param $text String: database error message.
399 function wfLogDBError( $text ) {
400 global $wgDBerrorLog, $wgDBname;
401 if ( $wgDBerrorLog ) {
402 $host = trim(`hostname`
);
403 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
404 wfErrorLog( $text, $wgDBerrorLog );
409 * Log to a file without getting "file size exceeded" signals.
411 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
412 * send lines to the specified port, prefixed by the specified prefix and a space.
414 function wfErrorLog( $text, $file ) {
415 if ( substr( $file, 0, 4 ) == 'udp:' ) {
416 # Needs the sockets extension
417 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
418 // IPv6 bracketed host
420 $port = intval( $m[3] );
421 $prefix = isset( $m[4] ) ?
$m[4] : false;
423 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
425 if ( !IP
::isIPv4( $host ) ) {
426 $host = gethostbyname( $host );
428 $port = intval( $m[3] );
429 $prefix = isset( $m[4] ) ?
$m[4] : false;
432 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
434 // Clean it up for the multiplexer
435 if ( strval( $prefix ) !== '' ) {
436 $text = preg_replace( '/^/m', $prefix . ' ', $text );
437 if ( substr( $text, -1 ) != "\n" ) {
442 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
446 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
447 socket_close( $sock );
449 wfSuppressWarnings();
450 $exists = file_exists( $file );
451 $size = $exists ?
filesize( $file ) : false;
452 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
453 error_log( $text, 3, $file );
462 function wfLogProfilingData() {
463 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
464 global $wgProfiler, $wgProfileLimit, $wgUser;
465 # Profiling must actually be enabled...
466 if( is_null( $wgProfiler ) ) {
469 # Get total page request time
471 $elapsed = $now - $wgRequestTime;
472 # Only show pages that longer than $wgProfileLimit time (default is 0)
473 if( $elapsed <= $wgProfileLimit ) {
476 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
478 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
479 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
481 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
482 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
484 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
485 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
488 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
490 // Don't unstub $wgUser at this late stage just for statistics purposes
491 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
492 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
495 $log = sprintf( "%s\t%04.3f\t%s\n",
496 gmdate( 'YmdHis' ), $elapsed,
497 urldecode( $wgRequest->getRequestURL() . $forward ) );
498 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
499 wfErrorLog( $log . $prof, $wgDebugLogFile );
504 * Check if the wiki read-only lock file is present. This can be used to lock
505 * off editing functions, but doesn't guarantee that the database will not be
509 function wfReadOnly() {
510 global $wgReadOnlyFile, $wgReadOnly;
512 if ( !is_null( $wgReadOnly ) ) {
513 return (bool)$wgReadOnly;
515 if ( $wgReadOnlyFile == '' ) {
518 // Set $wgReadOnly for faster access next time
519 if ( is_file( $wgReadOnlyFile ) ) {
520 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
524 return (bool)$wgReadOnly;
527 function wfReadOnlyReason() {
534 * Return a Language object from $langcode
535 * @param $langcode Mixed: either:
536 * - a Language object
537 * - code of the language to get the message for, if it is
538 * a valid code create a language for that language, if
539 * it is a string but not a valid code then make a basic
541 * - a boolean: if it's false then use the current users
542 * language (as a fallback for the old parameter
543 * functionality), or if it is true then use the wikis
544 * @return Language object
546 function wfGetLangObj( $langcode = false ) {
547 # Identify which language to get or create a language object for.
548 # Using is_object here due to Stub objects.
549 if( is_object( $langcode ) ) {
550 # Great, we already have the object (hopefully)!
554 global $wgContLang, $wgLanguageCode;
555 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
556 # $langcode is the language code of the wikis content language object.
557 # or it is a boolean and value is true
562 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
563 # $langcode is the language code of user language object.
564 # or it was a boolean and value is false
568 $validCodes = array_keys( Language
::getLanguageNames() );
569 if( in_array( $langcode, $validCodes ) ) {
570 # $langcode corresponds to a valid language.
571 return Language
::factory( $langcode );
574 # $langcode is a string, but not a valid language code; use content language.
575 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
580 * Use this instead of $wgContLang, when working with user interface.
581 * User interface is currently hard coded according to wiki content language
582 * in many ways, especially regarding to text direction. There is lots stuff
583 * to fix, hence this function to keep the old behaviour unless the global
584 * $wgBetterDirectionality is enabled (or removed when everything works).
586 function wfUILang() {
587 global $wgBetterDirectionality;
588 return wfGetLangObj( !$wgBetterDirectionality );
592 * This is the new function for getting translated interface messages.
593 * See the Message class for documentation how to use them.
594 * The intention is that this function replaces all old wfMsg* functions.
595 * @param $key \string Message key.
596 * Varargs: normal message parameters.
597 * @return \type{Message}
600 function wfMessage( $key /*...*/) {
601 $params = func_get_args();
602 array_shift( $params );
603 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
604 $params = $params[0];
606 return new Message( $key, $params );
610 * Get a message from anywhere, for the current user language.
612 * Use wfMsgForContent() instead if the message should NOT
613 * change depending on the user preferences.
615 * @param $key String: lookup key for the message, usually
616 * defined in languages/Language.php
618 * This function also takes extra optional parameters (not
619 * shown in the function definition), which can be used to
620 * insert variable text into the predefined message.
622 function wfMsg( $key ) {
623 $args = func_get_args();
624 array_shift( $args );
625 return wfMsgReal( $key, $args, true );
629 * Same as above except doesn't transform the message
631 function wfMsgNoTrans( $key ) {
632 $args = func_get_args();
633 array_shift( $args );
634 return wfMsgReal( $key, $args, true, false, false );
638 * Get a message from anywhere, for the current global language
639 * set with $wgLanguageCode.
641 * Use this if the message should NOT change dependent on the
642 * language set in the user's preferences. This is the case for
643 * most text written into logs, as well as link targets (such as
644 * the name of the copyright policy page). Link titles, on the
645 * other hand, should be shown in the UI language.
647 * Note that MediaWiki allows users to change the user interface
648 * language in their preferences, but a single installation
649 * typically only contains content in one language.
651 * Be wary of this distinction: If you use wfMsg() where you should
652 * use wfMsgForContent(), a user of the software may have to
653 * customize potentially hundreds of messages in
654 * order to, e.g., fix a link in every possible language.
656 * @param $key String: lookup key for the message, usually
657 * defined in languages/Language.php
659 function wfMsgForContent( $key ) {
660 global $wgForceUIMsgAsContentMsg;
661 $args = func_get_args();
662 array_shift( $args );
664 if( is_array( $wgForceUIMsgAsContentMsg ) &&
665 in_array( $key, $wgForceUIMsgAsContentMsg ) )
669 return wfMsgReal( $key, $args, true, $forcontent );
673 * Same as above except doesn't transform the message
675 function wfMsgForContentNoTrans( $key ) {
676 global $wgForceUIMsgAsContentMsg;
677 $args = func_get_args();
678 array_shift( $args );
680 if( is_array( $wgForceUIMsgAsContentMsg ) &&
681 in_array( $key, $wgForceUIMsgAsContentMsg ) )
685 return wfMsgReal( $key, $args, true, $forcontent, false );
689 * Get a message from the language file, for the UI elements
691 function wfMsgNoDB( $key ) {
692 $args = func_get_args();
693 array_shift( $args );
694 return wfMsgReal( $key, $args, false );
698 * Get a message from the language file, for the content
700 function wfMsgNoDBForContent( $key ) {
701 global $wgForceUIMsgAsContentMsg;
702 $args = func_get_args();
703 array_shift( $args );
705 if( is_array( $wgForceUIMsgAsContentMsg ) &&
706 in_array( $key, $wgForceUIMsgAsContentMsg ) )
710 return wfMsgReal( $key, $args, false, $forcontent );
715 * Really get a message
716 * @param $key String: key to get.
718 * @param $useDB Boolean
719 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
720 * @param $transform Boolean: Whether or not to transform the message.
721 * @return String: the requested message.
723 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
724 wfProfileIn( __METHOD__
);
725 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
726 $message = wfMsgReplaceArgs( $message, $args );
727 wfProfileOut( __METHOD__
);
732 * This function provides the message source for messages to be edited which are *not* stored in the database.
733 * @param $key String:
735 function wfMsgWeirdKey( $key ) {
736 $source = wfMsgGetKey( $key, false, true, false );
737 if ( wfEmptyMsg( $key, $source ) ) {
745 * Fetch a message string value, but don't replace any keys yet.
748 * @param $langCode String: Code of the language to get the message for, or
749 * behaves as a content language switch if it is a boolean.
750 * @param $transform Boolean: whether to parse magic words, etc.
753 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
754 global $wgMessageCache;
756 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
758 if ( !is_object( $wgMessageCache ) ) {
759 throw new MWException( 'Trying to get message before message cache is initialised' );
762 $message = $wgMessageCache->get( $key, $useDB, $langCode );
763 if( $message === false ) {
764 $message = '<' . htmlspecialchars( $key ) . '>';
765 } elseif ( $transform ) {
766 $message = $wgMessageCache->transform( $message );
772 * Replace message parameter keys on the given formatted output.
774 * @param $message String
779 function wfMsgReplaceArgs( $message, $args ) {
780 # Fix windows line-endings
781 # Some messages are split with explode("\n", $msg)
782 $message = str_replace( "\r", '', $message );
785 if ( count( $args ) ) {
786 if ( is_array( $args[0] ) ) {
787 $args = array_values( $args[0] );
789 $replacementKeys = array();
790 foreach( $args as $n => $param ) {
791 $replacementKeys['$' . ( $n +
1 )] = $param;
793 $message = strtr( $message, $replacementKeys );
800 * Return an HTML-escaped version of a message.
801 * Parameter replacements, if any, are done *after* the HTML-escaping,
802 * so parameters may contain HTML (eg links or form controls). Be sure
803 * to pre-escape them if you really do want plaintext, or just wrap
804 * the whole thing in htmlspecialchars().
807 * @param string ... parameters
810 function wfMsgHtml( $key ) {
811 $args = func_get_args();
812 array_shift( $args );
813 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
817 * Return an HTML version of message
818 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
819 * so parameters may contain HTML (eg links or form controls). Be sure
820 * to pre-escape them if you really do want plaintext, or just wrap
821 * the whole thing in htmlspecialchars().
824 * @param string ... parameters
827 function wfMsgWikiHtml( $key ) {
829 $args = func_get_args();
830 array_shift( $args );
831 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
835 * Returns message in the requested format
836 * @param $key String: key of the message
837 * @param $options Array: processing rules. Can take the following options:
838 * <i>parse</i>: parses wikitext to HTML
839 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
840 * p's added by parser or tidy
841 * <i>escape</i>: filters message through htmlspecialchars
842 * <i>escapenoentities</i>: same, but allows entity references like   through
843 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
844 * <i>parsemag</i>: transform the message using magic phrases
845 * <i>content</i>: fetch message for content language instead of interface
846 * Also can accept a single associative argument, of the form 'language' => 'xx':
847 * <i>language</i>: Language object or language code to fetch message for
848 * (overriden by <i>content</i>), its behaviour with parse, parseinline
849 * and parsemag is undefined.
850 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
852 function wfMsgExt( $key, $options ) {
855 $args = func_get_args();
856 array_shift( $args );
857 array_shift( $args );
858 $options = (array)$options;
860 foreach( $options as $arrayKey => $option ) {
861 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
862 # An unknown index, neither numeric nor "language"
863 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
864 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
865 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
866 'replaceafter', 'parsemag', 'content' ) ) ) {
867 # A numeric index with unknown value
868 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
872 if( in_array( 'content', $options, true ) ) {
875 } elseif( array_key_exists( 'language', $options ) ) {
877 $langCode = wfGetLangObj( $options['language'] );
883 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
885 if( !in_array( 'replaceafter', $options, true ) ) {
886 $string = wfMsgReplaceArgs( $string, $args );
889 if( in_array( 'parse', $options, true ) ) {
890 $string = $wgOut->parse( $string, true, !$forContent );
891 } elseif ( in_array( 'parseinline', $options, true ) ) {
892 $string = $wgOut->parse( $string, true, !$forContent );
894 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
897 } elseif ( in_array( 'parsemag', $options, true ) ) {
898 global $wgMessageCache;
899 if ( isset( $wgMessageCache ) ) {
900 $string = $wgMessageCache->transform( $string,
902 is_object( $langCode ) ?
$langCode : null );
906 if ( in_array( 'escape', $options, true ) ) {
907 $string = htmlspecialchars ( $string );
908 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
909 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
912 if( in_array( 'replaceafter', $options, true ) ) {
913 $string = wfMsgReplaceArgs( $string, $args );
921 * Just like exit() but makes a note of it.
922 * Commits open transactions except if the error parameter is set
924 * @deprecated Please return control to the caller or throw an exception. Will
925 * be removed in 1.19.
927 function wfAbruptExit( $error = false ) {
928 static $called = false;
934 wfDeprecated( __FUNCTION__
);
935 $bt = wfDebugBacktrace();
937 for( $i = 0; $i < count( $bt ); $i++
) {
938 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
939 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
940 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
943 wfDebug( "WARNING: Abrupt exit\n" );
946 wfLogProfilingData();
949 wfGetLB()->closeAll();
955 * @deprecated Please return control the caller or throw an exception. Will
956 * be removed in 1.19.
958 function wfErrorExit() {
959 wfDeprecated( __FUNCTION__
);
960 wfAbruptExit( true );
964 * Print a simple message and die, returning nonzero to the shell if any.
965 * Plain die() fails to return nonzero to the shell if you pass a string.
968 function wfDie( $msg = '' ) {
974 * Throw a debugging exception. This function previously once exited the process,
975 * but now throws an exception instead, with similar results.
977 * @param $msg String: message shown when dieing.
979 function wfDebugDieBacktrace( $msg = '' ) {
980 throw new MWException( $msg );
984 * Fetch server name for use in error reporting etc.
985 * Use real server name if available, so we know which machine
986 * in a server farm generated the current page.
989 function wfHostname() {
991 if ( is_null( $host ) ) {
992 if ( function_exists( 'posix_uname' ) ) {
993 // This function not present on Windows
994 $uname = @posix_uname
();
998 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
999 $host = $uname['nodename'];
1000 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1001 # Windows computer name
1002 $host = getenv( 'COMPUTERNAME' );
1004 # This may be a virtual server.
1005 $host = $_SERVER['SERVER_NAME'];
1012 * Returns a HTML comment with the elapsed time since request.
1013 * This method has no side effects.
1016 function wfReportTime() {
1017 global $wgRequestTime, $wgShowHostnames;
1020 $elapsed = $now - $wgRequestTime;
1022 return $wgShowHostnames
1023 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1024 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1028 * Safety wrapper for debug_backtrace().
1030 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1031 * murky circumstances, which may be triggered in part by stub objects
1032 * or other fancy talkin'.
1034 * Will return an empty array if Zend Optimizer is detected or if
1035 * debug_backtrace is disabled, otherwise the output from
1036 * debug_backtrace() (trimmed).
1038 * @return array of backtrace information
1040 function wfDebugBacktrace() {
1041 static $disabled = null;
1043 if( extension_loaded( 'Zend Optimizer' ) ) {
1044 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1048 if ( is_null( $disabled ) ) {
1050 $functions = explode( ',', ini_get( 'disable_functions' ) );
1051 $functions = array_map( 'trim', $functions );
1052 $functions = array_map( 'strtolower', $functions );
1053 if ( in_array( 'debug_backtrace', $functions ) ) {
1054 wfDebug( "debug_backtrace is in disabled_functions\n" );
1062 return array_slice( debug_backtrace(), 1 );
1065 function wfBacktrace() {
1066 global $wgCommandLineMode;
1068 if ( $wgCommandLineMode ) {
1073 $backtrace = wfDebugBacktrace();
1074 foreach( $backtrace as $call ) {
1075 if( isset( $call['file'] ) ) {
1076 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1077 $file = $f[count( $f ) - 1];
1081 if( isset( $call['line'] ) ) {
1082 $line = $call['line'];
1086 if ( $wgCommandLineMode ) {
1087 $msg .= "$file line $line calls ";
1089 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1091 if( !empty( $call['class'] ) ) {
1092 $msg .= $call['class'] . '::';
1094 $msg .= $call['function'] . '()';
1096 if ( $wgCommandLineMode ) {
1102 if ( $wgCommandLineMode ) {
1112 /* Some generic result counters, pulled out of SearchEngine */
1118 function wfShowingResults( $offset, $limit ) {
1122 array( 'parseinline' ),
1123 $wgLang->formatNum( $limit ),
1124 $wgLang->formatNum( $offset +
1 )
1131 function wfShowingResultsNum( $offset, $limit, $num ) {
1134 'showingresultsnum',
1135 array( 'parseinline' ),
1136 $wgLang->formatNum( $limit ),
1137 $wgLang->formatNum( $offset +
1 ),
1138 $wgLang->formatNum( $num )
1143 * Generate (prev x| next x) (20|50|100...) type links for paging
1144 * @param $offset String
1145 * @param $limit Integer
1146 * @param $link String
1147 * @param $query String: optional URL query parameter string
1148 * @param $atend Bool: optional param for specified if this is the last page
1150 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1152 $fmtLimit = $wgLang->formatNum( $limit );
1153 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1154 # Get prev/next link display text
1155 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1156 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1157 # Get prev/next link title text
1158 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1159 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1160 # Fetch the title object
1161 if( is_object( $link ) ) {
1164 $title = Title
::newFromText( $link );
1165 if( is_null( $title ) ) {
1169 # Make 'previous' link
1170 if( 0 != $offset ) {
1171 $po = $offset - $limit;
1172 $po = max( $po, 0 );
1173 $q = "limit={$limit}&offset={$po}";
1174 if( $query != '' ) {
1177 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1182 $no = $offset +
$limit;
1183 $q = "limit={$limit}&offset={$no}";
1184 if( $query != '' ) {
1190 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1192 # Make links to set number of items per page
1193 $nums = $wgLang->pipeList( array(
1194 wfNumLink( $offset, 20, $title, $query ),
1195 wfNumLink( $offset, 50, $title, $query ),
1196 wfNumLink( $offset, 100, $title, $query ),
1197 wfNumLink( $offset, 250, $title, $query ),
1198 wfNumLink( $offset, 500, $title, $query )
1200 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1204 * Generate links for (20|50|100...) items-per-page links
1205 * @param $offset String
1206 * @param $limit Integer
1207 * @param $title Title
1208 * @param $query String: optional URL query parameter string
1210 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1212 if( $query == '' ) {
1217 $q .= "limit={$limit}&offset={$offset}";
1218 $fmtLimit = $wgLang->formatNum( $limit );
1219 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1220 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1226 * @todo FIXME: we may want to blacklist some broken browsers
1228 * @return bool Whereas client accept gzip compression
1230 function wfClientAcceptsGzip() {
1231 static $result = null;
1232 if ( $result === null ) {
1234 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1235 # FIXME: we may want to blacklist some broken browsers
1238 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1239 $_SERVER['HTTP_ACCEPT_ENCODING'],
1243 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1247 wfDebug( " accepts gzip\n" );
1256 * Obtain the offset and limit values from the request string;
1257 * used in special pages
1259 * @param $deflimit Default limit if none supplied
1260 * @param $optionname Name of a user preference to check against
1264 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1266 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1270 * Escapes the given text so that it may be output using addWikiText()
1271 * without any linking, formatting, etc. making its way through. This
1272 * is achieved by substituting certain characters with HTML entities.
1273 * As required by the callers, <nowiki> is not used. It currently does
1274 * not filter out characters which have special meaning only at the
1275 * start of a line, such as "*".
1277 * @param $text String: text to be escaped
1279 function wfEscapeWikiText( $text ) {
1280 $text = str_replace(
1281 array( '[', '|', ']', '\'', 'ISBN ',
1282 'RFC ', '://', "\n=", '{{', '}}' ),
1283 array( '[', '|', ']', ''', 'ISBN ',
1284 'RFC ', '://', "\n=", '{{', '}}' ),
1285 htmlspecialchars( $text )
1295 return microtime( true );
1299 * Sets dest to source and returns the original value of dest
1300 * If source is NULL, it just returns the value, it doesn't set the variable
1302 function wfSetVar( &$dest, $source ) {
1304 if ( !is_null( $source ) ) {
1311 * As for wfSetVar except setting a bit
1313 function wfSetBit( &$dest, $bit, $state = true ) {
1314 $temp = (bool)( $dest & $bit );
1315 if ( !is_null( $state ) ) {
1326 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1327 * "days=7&limit=100". Options in the first array override options in the second.
1328 * Options set to "" will not be output.
1330 function wfArrayToCGI( $array1, $array2 = null ) {
1331 if ( !is_null( $array2 ) ) {
1332 $array1 = $array1 +
$array2;
1336 foreach ( $array1 as $key => $value ) {
1337 if ( $value !== '' ) {
1341 if ( is_array( $value ) ) {
1343 foreach ( $value as $v ) {
1344 $cgi .= ( $firstTime ?
'' : '&') .
1345 urlencode( $key . '[]' ) . '=' .
1350 if ( is_object( $value ) ) {
1351 $value = $value->__toString();
1353 $cgi .= urlencode( $key ) . '=' .
1354 urlencode( $value );
1362 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1363 * its argument and returns the same string in array form. This allows compa-
1364 * tibility with legacy functions that accept raw query strings instead of nice
1365 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1366 * valid query strings, or it will explode.
1368 * @param $query String: query string
1369 * @return array Array version of input
1371 function wfCgiToArray( $query ) {
1372 if( isset( $query[0] ) && $query[0] == '?' ) {
1373 $query = substr( $query, 1 );
1375 $bits = explode( '&', $query );
1377 foreach( $bits as $bit ) {
1381 list( $key, $value ) = explode( '=', $bit );
1382 $key = urldecode( $key );
1383 $value = urldecode( $value );
1384 $ret[$key] = $value;
1390 * Append a query string to an existing URL, which may or may not already
1391 * have query string parameters already. If so, they will be combined.
1393 * @param $url String
1394 * @param $query Mixed: string or associative array
1397 function wfAppendQuery( $url, $query ) {
1398 if ( is_array( $query ) ) {
1399 $query = wfArrayToCGI( $query );
1401 if( $query != '' ) {
1402 if( false === strpos( $url, '?' ) ) {
1413 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1414 * and $wgProto are correct.
1416 * @todo this won't work with current-path-relative URLs
1417 * like "subdir/foo.html", etc.
1419 * @param $url String: either fully-qualified or a local path + query
1420 * @return string Fully-qualified URL
1422 function wfExpandUrl( $url ) {
1423 if( substr( $url, 0, 2 ) == '//' ) {
1425 return $wgProto . ':' . $url;
1426 } elseif( substr( $url, 0, 1 ) == '/' ) {
1428 return $wgServer . $url;
1435 * Windows-compatible version of escapeshellarg()
1436 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1437 * function puts single quotes in regardless of OS.
1439 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1440 * earlier distro releases of PHP)
1442 function wfEscapeShellArg( ) {
1443 wfInitShellLocale();
1445 $args = func_get_args();
1448 foreach ( $args as $arg ) {
1455 if ( wfIsWindows() ) {
1456 // Escaping for an MSVC-style command line parser
1457 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1458 // Double the backslashes before any double quotes. Escape the double quotes.
1459 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1462 foreach ( $tokens as $token ) {
1463 if ( $iteration %
2 == 1 ) {
1464 // Delimiter, a double quote preceded by zero or more slashes
1465 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1466 } elseif ( $iteration %
4 == 2 ) {
1467 // ^ in $token will be outside quotes, need to be escaped
1468 $arg .= str_replace( '^', '^^', $token );
1469 } else { // $iteration % 4 == 0
1470 // ^ in $token will appear inside double quotes, so leave as is
1475 // Double the backslashes before the end of the string, because
1476 // we will soon add a quote
1478 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1479 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1482 // Add surrounding quotes
1483 $retVal .= '"' . $arg . '"';
1485 $retVal .= escapeshellarg( $arg );
1492 * wfMerge attempts to merge differences between three texts.
1493 * Returns true for a clean merge and false for failure or a conflict.
1495 function wfMerge( $old, $mine, $yours, &$result ) {
1498 # This check may also protect against code injection in
1499 # case of broken installations.
1500 wfSuppressWarnings();
1501 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1502 wfRestoreWarnings();
1505 wfDebug( "diff3 not found\n" );
1509 # Make temporary files
1511 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1512 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1513 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1515 fwrite( $oldtextFile, $old );
1516 fclose( $oldtextFile );
1517 fwrite( $mytextFile, $mine );
1518 fclose( $mytextFile );
1519 fwrite( $yourtextFile, $yours );
1520 fclose( $yourtextFile );
1522 # Check for a conflict
1523 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1524 wfEscapeShellArg( $mytextName ) . ' ' .
1525 wfEscapeShellArg( $oldtextName ) . ' ' .
1526 wfEscapeShellArg( $yourtextName );
1527 $handle = popen( $cmd, 'r' );
1529 if( fgets( $handle, 1024 ) ) {
1537 $cmd = $wgDiff3 . ' -a -e --merge ' .
1538 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1539 $handle = popen( $cmd, 'r' );
1542 $data = fread( $handle, 8192 );
1543 if ( strlen( $data ) == 0 ) {
1549 unlink( $mytextName );
1550 unlink( $oldtextName );
1551 unlink( $yourtextName );
1553 if ( $result === '' && $old !== '' && !$conflict ) {
1554 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1561 * Returns unified plain-text diff of two texts.
1562 * Useful for machine processing of diffs.
1563 * @param $before String: the text before the changes.
1564 * @param $after String: the text after the changes.
1565 * @param $params String: command-line options for the diff command.
1566 * @return String: unified diff of $before and $after
1568 function wfDiff( $before, $after, $params = '-u' ) {
1569 if ( $before == $after ) {
1574 wfSuppressWarnings();
1575 $haveDiff = $wgDiff && file_exists( $wgDiff );
1576 wfRestoreWarnings();
1578 # This check may also protect against code injection in
1579 # case of broken installations.
1581 wfDebug( "diff executable not found\n" );
1582 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1583 $format = new UnifiedDiffFormatter();
1584 return $format->format( $diffs );
1587 # Make temporary files
1589 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1590 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1592 fwrite( $oldtextFile, $before );
1593 fclose( $oldtextFile );
1594 fwrite( $newtextFile, $after );
1595 fclose( $newtextFile );
1597 // Get the diff of the two files
1598 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1600 $h = popen( $cmd, 'r' );
1605 $data = fread( $h, 8192 );
1606 if ( strlen( $data ) == 0 ) {
1614 unlink( $oldtextName );
1615 unlink( $newtextName );
1617 // Kill the --- and +++ lines. They're not useful.
1618 $diff_lines = explode( "\n", $diff );
1619 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1620 unset( $diff_lines[0] );
1622 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1623 unset( $diff_lines[1] );
1626 $diff = implode( "\n", $diff_lines );
1632 * A wrapper around the PHP function var_export().
1633 * Either print it or add it to the regular output ($wgOut).
1635 * @param $var A PHP variable to dump.
1637 function wfVarDump( $var ) {
1639 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1640 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1643 $wgOut->addHTML( $s );
1648 * Provide a simple HTTP error.
1650 function wfHttpError( $code, $label, $desc ) {
1653 header( "HTTP/1.0 $code $label" );
1654 header( "Status: $code $label" );
1655 $wgOut->sendCacheControl();
1657 header( 'Content-type: text/html; charset=utf-8' );
1658 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1659 '<html><head><title>' .
1660 htmlspecialchars( $label ) .
1661 '</title></head><body><h1>' .
1662 htmlspecialchars( $label ) .
1664 nl2br( htmlspecialchars( $desc ) ) .
1665 "</p></body></html>\n";
1669 * Clear away any user-level output buffers, discarding contents.
1671 * Suitable for 'starting afresh', for instance when streaming
1672 * relatively large amounts of data without buffering, or wanting to
1673 * output image files without ob_gzhandler's compression.
1675 * The optional $resetGzipEncoding parameter controls suppression of
1676 * the Content-Encoding header sent by ob_gzhandler; by default it
1677 * is left. See comments for wfClearOutputBuffers() for why it would
1680 * Note that some PHP configuration options may add output buffer
1681 * layers which cannot be removed; these are left in place.
1683 * @param $resetGzipEncoding Bool
1685 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1686 if( $resetGzipEncoding ) {
1687 // Suppress Content-Encoding and Content-Length
1688 // headers from 1.10+s wfOutputHandler
1689 global $wgDisableOutputCompression;
1690 $wgDisableOutputCompression = true;
1692 while( $status = ob_get_status() ) {
1693 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1694 // Probably from zlib.output_compression or other
1695 // PHP-internal setting which can't be removed.
1697 // Give up, and hope the result doesn't break
1701 if( !ob_end_clean() ) {
1702 // Could not remove output buffer handler; abort now
1703 // to avoid getting in some kind of infinite loop.
1706 if( $resetGzipEncoding ) {
1707 if( $status['name'] == 'ob_gzhandler' ) {
1708 // Reset the 'Content-Encoding' field set by this handler
1709 // so we can start fresh.
1710 header( 'Content-Encoding:' );
1718 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1720 * Clear away output buffers, but keep the Content-Encoding header
1721 * produced by ob_gzhandler, if any.
1723 * This should be used for HTTP 304 responses, where you need to
1724 * preserve the Content-Encoding header of the real result, but
1725 * also need to suppress the output of ob_gzhandler to keep to spec
1726 * and avoid breaking Firefox in rare cases where the headers and
1727 * body are broken over two packets.
1729 function wfClearOutputBuffers() {
1730 wfResetOutputBuffers( false );
1734 * Converts an Accept-* header into an array mapping string values to quality
1737 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1738 # No arg means accept anything (per HTTP spec)
1740 return array( $def => 1.0 );
1745 $parts = explode( ',', $accept );
1747 foreach( $parts as $part ) {
1748 # FIXME: doesn't deal with params like 'text/html; level=1'
1749 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1751 if( !isset( $qpart ) ) {
1752 $prefs[$value] = 1.0;
1753 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1754 $prefs[$value] = floatval( $match[1] );
1762 * Checks if a given MIME type matches any of the keys in the given
1763 * array. Basic wildcards are accepted in the array keys.
1765 * Returns the matching MIME type (or wildcard) if a match, otherwise
1768 * @param $type String
1769 * @param $avail Array
1773 function mimeTypeMatch( $type, $avail ) {
1774 if( array_key_exists( $type, $avail ) ) {
1777 $parts = explode( '/', $type );
1778 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1779 return $parts[0] . '/*';
1780 } elseif( array_key_exists( '*/*', $avail ) ) {
1789 * Returns the 'best' match between a client's requested internet media types
1790 * and the server's list of available types. Each list should be an associative
1791 * array of type to preference (preference is a float between 0.0 and 1.0).
1792 * Wildcards in the types are acceptable.
1794 * @param $cprefs Array: client's acceptable type list
1795 * @param $sprefs Array: server's offered types
1798 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1799 * XXX: generalize to negotiate other stuff
1801 function wfNegotiateType( $cprefs, $sprefs ) {
1804 foreach( array_keys($sprefs) as $type ) {
1805 $parts = explode( '/', $type );
1806 if( $parts[1] != '*' ) {
1807 $ckey = mimeTypeMatch( $type, $cprefs );
1809 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1814 foreach( array_keys( $cprefs ) as $type ) {
1815 $parts = explode( '/', $type );
1816 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1817 $skey = mimeTypeMatch( $type, $sprefs );
1819 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1827 foreach( array_keys( $combine ) as $type ) {
1828 if( $combine[$type] > $bestq ) {
1830 $bestq = $combine[$type];
1839 * Returns an array where the values in the first array are replaced by the
1840 * values in the second array with the corresponding keys
1844 function wfArrayLookup( $a, $b ) {
1845 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1849 * Convenience function; returns MediaWiki timestamp for the present time.
1852 function wfTimestampNow() {
1854 return wfTimestamp( TS_MW
, time() );
1858 * Reference-counted warning suppression
1860 function wfSuppressWarnings( $end = false ) {
1861 static $suppressCount = 0;
1862 static $originalLevel = false;
1865 if ( $suppressCount ) {
1867 if ( !$suppressCount ) {
1868 error_reporting( $originalLevel );
1872 if ( !$suppressCount ) {
1873 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1880 * Restore error level to previous value
1882 function wfRestoreWarnings() {
1883 wfSuppressWarnings( true );
1886 # Autodetect, convert and provide timestamps of various types
1889 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1891 define( 'TS_UNIX', 0 );
1894 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1896 define( 'TS_MW', 1 );
1899 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1901 define( 'TS_DB', 2 );
1904 * RFC 2822 format, for E-mail and HTTP headers
1906 define( 'TS_RFC2822', 3 );
1909 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1911 * This is used by Special:Export
1913 define( 'TS_ISO_8601', 4 );
1916 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1918 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1919 * DateTime tag and page 36 for the DateTimeOriginal and
1920 * DateTimeDigitized tags.
1922 define( 'TS_EXIF', 5 );
1925 * Oracle format time.
1927 define( 'TS_ORACLE', 6 );
1930 * Postgres format time.
1932 define( 'TS_POSTGRES', 7 );
1937 define( 'TS_DB2', 8 );
1940 * ISO 8601 basic format with no timezone: 19860209T200000Z
1942 * This is used by ResourceLoader
1944 define( 'TS_ISO_8601_BASIC', 9 );
1947 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1948 * function will autodetect which format is supplied and act
1950 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1951 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1953 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1961 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1963 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1965 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1967 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1970 $strtime = "@$ts"; // Undocumented?
1971 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1972 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1973 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1974 str_replace( '+00:00', 'UTC', $ts ) );
1975 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1977 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1979 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1981 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1983 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1985 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1986 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1987 '[ \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
1988 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1989 # The regex is a superset of rfc2822 for readability
1990 $strtime = strtok( $ts, ';' );
1991 } 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 ) ) {
1994 } 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 ) ) {
1998 # Bogus value; fall back to the epoch...
1999 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2006 static $formats = array(
2009 TS_DB
=> 'Y-m-d H:i:s',
2010 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2011 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2012 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2013 TS_RFC2822
=> 'D, d M Y H:i:s',
2014 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2015 TS_POSTGRES
=> 'Y-m-d H:i:s',
2016 TS_DB2
=> 'Y-m-d H:i:s',
2019 if ( !isset( $formats[$outputtype] ) ) {
2020 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2023 if ( function_exists( "date_create" ) ) {
2024 if ( count( $da ) ) {
2025 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2026 (int)$da[1], (int)$da[2], (int)$da[3],
2027 (int)$da[4], (int)$da[5], (int)$da[6]);
2029 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2030 } elseif ( $strtime ) {
2031 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2037 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2041 $output = $d->format( $formats[$outputtype] );
2043 if ( count( $da ) ) {
2044 // Warning! gmmktime() acts oddly if the month or day is set to 0
2045 // We may want to handle that explicitly at some point
2046 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2047 (int)$da[2], (int)$da[3], (int)$da[1] );
2048 } elseif ( $strtime ) {
2049 $uts = strtotime( $strtime );
2052 if ( $uts === false ) {
2053 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2057 if ( TS_UNIX
== $outputtype ) {
2060 $output = gmdate( $formats[$outputtype], $uts );
2063 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2071 * Return a formatted timestamp, or null if input is null.
2072 * For dealing with nullable timestamp columns in the database.
2073 * @param $outputtype Integer
2077 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2078 if( is_null( $ts ) ) {
2081 return wfTimestamp( $outputtype, $ts );
2086 * Check if the operating system is Windows
2088 * @return Bool: true if it's Windows, False otherwise.
2090 function wfIsWindows() {
2091 static $isWindows = null;
2092 if ( $isWindows === null ) {
2093 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2099 * Swap two variables
2101 function swap( &$x, &$y ) {
2107 function wfGetCachedNotice( $name ) {
2108 global $wgOut, $wgRenderHashAppend, $parserMemc;
2109 $fname = 'wfGetCachedNotice';
2110 wfProfileIn( $fname );
2114 if( $name === 'default' ) {
2116 global $wgSiteNotice;
2117 $notice = $wgSiteNotice;
2118 if( empty( $notice ) ) {
2119 wfProfileOut( $fname );
2123 $notice = wfMsgForContentNoTrans( $name );
2124 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2125 wfProfileOut( $fname );
2130 // Use the extra hash appender to let eg SSL variants separately cache.
2131 $key = wfMemcKey( $name . $wgRenderHashAppend );
2132 $cachedNotice = $parserMemc->get( $key );
2133 if( is_array( $cachedNotice ) ) {
2134 if( md5( $notice ) == $cachedNotice['hash'] ) {
2135 $notice = $cachedNotice['html'];
2144 if( is_object( $wgOut ) ) {
2145 $parsed = $wgOut->parse( $notice );
2146 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2149 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2153 $notice = '<div id="localNotice">' .$notice . '</div>';
2154 wfProfileOut( $fname );
2158 function wfGetNamespaceNotice() {
2162 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2166 $fname = 'wfGetNamespaceNotice';
2167 wfProfileIn( $fname );
2169 $key = 'namespacenotice-' . $wgTitle->getNsText();
2170 $namespaceNotice = wfGetCachedNotice( $key );
2171 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2172 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2174 $namespaceNotice = '';
2177 wfProfileOut( $fname );
2178 return $namespaceNotice;
2181 function wfGetSiteNotice() {
2183 $fname = 'wfGetSiteNotice';
2184 wfProfileIn( $fname );
2187 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2188 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2189 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2191 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2192 if( !$anonNotice ) {
2193 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2195 $siteNotice = $anonNotice;
2198 if( !$siteNotice ) {
2199 $siteNotice = wfGetCachedNotice( 'default' );
2203 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2204 wfProfileOut( $fname );
2209 * BC wrapper for MimeMagic::singleton()
2210 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2212 function &wfGetMimeMagic() {
2213 wfDeprecated( __FUNCTION__
);
2214 return MimeMagic
::singleton();
2218 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2219 * TEMP environment variables are then checked in sequence, and if none are set
2220 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2221 * or C:\Windows\Temp for Windows and hope for the best.
2222 * It is common to call it with tempnam().
2224 * NOTE: When possible, use instead the tmpfile() function to create
2225 * temporary files to avoid race conditions on file creation, etc.
2229 function wfTempDir() {
2230 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2231 $tmp = getenv( $var );
2232 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2236 if( function_exists( 'sys_get_temp_dir' ) ) {
2237 return sys_get_temp_dir();
2240 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2244 * Make directory, and make all parent directories if they don't exist
2246 * @param $dir String: full path to directory to create
2247 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2248 * @param $caller String: optional caller param for debugging.
2251 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2252 global $wgDirectoryMode;
2254 if ( !is_null( $caller ) ) {
2255 wfDebug( "$caller: called wfMkdirParents($dir)" );
2258 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2262 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2264 if ( is_null( $mode ) ) {
2265 $mode = $wgDirectoryMode;
2268 // Turn off the normal warning, we're doing our own below
2269 wfSuppressWarnings();
2270 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2271 wfRestoreWarnings();
2274 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2275 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2281 * Increment a statistics counter
2283 function wfIncrStats( $key ) {
2284 global $wgStatsMethod;
2286 if( $wgStatsMethod == 'udp' ) {
2287 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2290 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2291 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2295 strlen( $statline ),
2301 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2302 wfSuppressWarnings();
2306 strlen( $statline ),
2311 wfRestoreWarnings();
2312 } elseif( $wgStatsMethod == 'cache' ) {
2314 $key = wfMemcKey( 'stats', $key );
2315 if ( is_null( $wgMemc->incr( $key ) ) ) {
2316 $wgMemc->add( $key, 1 );
2324 * @param $nr Mixed: the number to format
2325 * @param $acc Integer: the number of digits after the decimal point, default 2
2326 * @param $round Boolean: whether or not to round the value, default true
2329 function wfPercent( $nr, $acc = 2, $round = true ) {
2330 $ret = sprintf( "%.${acc}f", $nr );
2331 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2335 * Encrypt a username/password.
2337 * @param $userid Integer: ID of the user
2338 * @param $password String: password of the user
2339 * @return String: hashed password
2340 * @deprecated Use User::crypt() or User::oldCrypt() instead
2342 function wfEncryptPassword( $userid, $password ) {
2343 wfDeprecated(__FUNCTION__
);
2344 # Just wrap around User::oldCrypt()
2345 return User
::oldCrypt( $password, $userid );
2349 * Appends to second array if $value differs from that in $default
2351 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2352 if ( is_null( $changed ) ) {
2353 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2355 if ( $default[$key] !== $value ) {
2356 $changed[$key] = $value;
2361 * Since wfMsg() and co suck, they don't return false if the message key they
2362 * looked up didn't exist but a XHTML string, this function checks for the
2363 * nonexistance of messages by looking at wfMsg() output
2365 * @param $key String: the message key looked up
2366 * @return Boolean True if the message *doesn't* exist.
2368 function wfEmptyMsg( $key ) {
2369 global $wgMessageCache;
2370 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2374 * Find out whether or not a mixed variable exists in a string
2376 * @param $needle String
2377 * @param $str String
2380 function in_string( $needle, $str ) {
2381 return strpos( $str, $needle ) !== false;
2384 function wfSpecialList( $page, $details ) {
2386 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2387 return $page . $details;
2391 * Returns a regular expression of url protocols
2395 function wfUrlProtocols() {
2396 global $wgUrlProtocols;
2398 static $retval = null;
2399 if ( !is_null( $retval ) ) {
2403 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2404 // with LocalSettings files from 1.5
2405 if ( is_array( $wgUrlProtocols ) ) {
2406 $protocols = array();
2407 foreach ( $wgUrlProtocols as $protocol ) {
2408 $protocols[] = preg_quote( $protocol, '/' );
2411 $retval = implode( '|', $protocols );
2413 $retval = $wgUrlProtocols;
2419 * Safety wrapper around ini_get() for boolean settings.
2420 * The values returned from ini_get() are pre-normalized for settings
2421 * set via php.ini or php_flag/php_admin_flag... but *not*
2422 * for those set via php_value/php_admin_value.
2424 * It's fairly common for people to use php_value instead of php_flag,
2425 * which can leave you with an 'off' setting giving a false positive
2426 * for code that just takes the ini_get() return value as a boolean.
2428 * To make things extra interesting, setting via php_value accepts
2429 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2430 * Unrecognized values go false... again opposite PHP's own coercion
2431 * from string to bool.
2433 * Luckily, 'properly' set settings will always come back as '0' or '1',
2434 * so we only have to worry about them and the 'improper' settings.
2436 * I frickin' hate PHP... :P
2438 * @param $setting String
2441 function wfIniGetBool( $setting ) {
2442 $val = ini_get( $setting );
2443 // 'on' and 'true' can't have whitespace around them, but '1' can.
2444 return strtolower( $val ) == 'on'
2445 ||
strtolower( $val ) == 'true'
2446 ||
strtolower( $val ) == 'yes'
2447 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2451 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2452 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2454 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2456 * @return Bool - Whether or not the extension is loaded
2458 function wfDl( $extension ) {
2459 if( extension_loaded( $extension ) ) {
2463 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2464 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2467 wfSuppressWarnings();
2468 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2469 wfRestoreWarnings();
2471 return extension_loaded( $extension );
2475 * Execute a shell command, with time and memory limits mirrored from the PHP
2476 * configuration if supported.
2477 * @param $cmd String Command line, properly escaped for shell.
2478 * @param &$retval optional, will receive the program's exit code.
2479 * (non-zero is usually failure)
2480 * @param $environ Array optional environment variables which should be
2481 * added to the executed command environment.
2482 * @return collected stdout as a string (trailing newlines stripped)
2484 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2485 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2488 if ( is_null( $disabled ) ) {
2490 if( wfIniGetBool( 'safe_mode' ) ) {
2491 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2492 $disabled = 'safemode';
2494 $functions = explode( ',', ini_get( 'disable_functions' ) );
2495 $functions = array_map( 'trim', $functions );
2496 $functions = array_map( 'strtolower', $functions );
2497 if ( in_array( 'passthru', $functions ) ) {
2498 wfDebug( "passthru is in disabled_functions\n" );
2499 $disabled = 'passthru';
2505 return $disabled == 'safemode' ?
2506 'Unable to run external programs in safe mode.' :
2507 'Unable to run external programs, passthru() is disabled.';
2510 wfInitShellLocale();
2513 foreach( $environ as $k => $v ) {
2514 if ( wfIsWindows() ) {
2515 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2516 * appear in the environment variable, so we must use carat escaping as documented in
2517 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2518 * Note however that the quote isn't listed there, but is needed, and the parentheses
2519 * are listed there but doesn't appear to need it.
2521 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . ' && ';
2523 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2524 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2526 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2529 $cmd = $envcmd . $cmd;
2531 if ( wfIsWindows() ) {
2532 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2533 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2535 # Hack to work around PHP's flawed invocation of cmd.exe
2536 # http://news.php.net/php.internals/21796
2537 # Windows 9x doesn't accept any kind of quotes
2538 $cmd = '"' . $cmd . '"';
2540 } elseif ( php_uname( 's' ) == 'Linux' ) {
2541 $time = intval( $wgMaxShellTime );
2542 $mem = intval( $wgMaxShellMemory );
2543 $filesize = intval( $wgMaxShellFileSize );
2545 if ( $time > 0 && $mem > 0 ) {
2546 $script = "$IP/bin/ulimit4.sh";
2547 if ( is_executable( $script ) ) {
2548 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2552 wfDebug( "wfShellExec: $cmd\n" );
2554 $retval = 1; // error by default?
2556 passthru( $cmd, $retval );
2557 $output = ob_get_contents();
2560 if ( $retval == 127 ) {
2561 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2567 * Workaround for http://bugs.php.net/bug.php?id=45132
2568 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2570 function wfInitShellLocale() {
2571 static $done = false;
2576 global $wgShellLocale;
2577 if ( !wfIniGetBool( 'safe_mode' ) ) {
2578 putenv( "LC_CTYPE=$wgShellLocale" );
2579 setlocale( LC_CTYPE
, $wgShellLocale );
2584 * This function works like "use VERSION" in Perl, the program will die with a
2585 * backtrace if the current version of PHP is less than the version provided
2587 * This is useful for extensions which due to their nature are not kept in sync
2588 * with releases, and might depend on other versions of PHP than the main code
2590 * Note: PHP might die due to parsing errors in some cases before it ever
2591 * manages to call this function, such is life
2593 * @see perldoc -f use
2595 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2598 function wfUsePHP( $req_ver ) {
2599 $php_ver = PHP_VERSION
;
2601 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2602 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2607 * This function works like "use VERSION" in Perl except it checks the version
2608 * of MediaWiki, the program will die with a backtrace if the current version
2609 * of MediaWiki is less than the version provided.
2611 * This is useful for extensions which due to their nature are not kept in sync
2614 * @see perldoc -f use
2616 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2619 function wfUseMW( $req_ver ) {
2622 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2623 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2628 * Return the final portion of a pathname.
2629 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2630 * http://bugs.php.net/bug.php?id=33898
2632 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2633 * We'll consider it so always, as we don't want \s in our Unix paths either.
2635 * @param $path String
2636 * @param $suffix String: to remove if present
2639 function wfBaseName( $path, $suffix = '' ) {
2640 $encSuffix = ( $suffix == '' )
2642 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2644 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2652 * Generate a relative path name to the given file.
2653 * May explode on non-matching case-insensitive paths,
2654 * funky symlinks, etc.
2656 * @param $path String: absolute destination path including target filename
2657 * @param $from String: Absolute source path, directory only
2660 function wfRelativePath( $path, $from ) {
2661 // Normalize mixed input on Windows...
2662 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2663 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2665 // Trim trailing slashes -- fix for drive root
2666 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2667 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2669 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2670 $against = explode( DIRECTORY_SEPARATOR
, $from );
2672 if( $pieces[0] !== $against[0] ) {
2673 // Non-matching Windows drive letters?
2674 // Return a full path.
2678 // Trim off common prefix
2679 while( count( $pieces ) && count( $against )
2680 && $pieces[0] == $against[0] ) {
2681 array_shift( $pieces );
2682 array_shift( $against );
2685 // relative dots to bump us to the parent
2686 while( count( $against ) ) {
2687 array_unshift( $pieces, '..' );
2688 array_shift( $against );
2691 array_push( $pieces, wfBaseName( $path ) );
2693 return implode( DIRECTORY_SEPARATOR
, $pieces );
2697 * Backwards array plus for people who haven't bothered to read the PHP manual
2698 * XXX: will not darn your socks for you.
2700 * @param $array1 Array
2701 * @param [$array2, [...]] Arrays
2704 function wfArrayMerge( $array1/* ... */ ) {
2705 $args = func_get_args();
2706 $args = array_reverse( $args, true );
2708 foreach ( $args as $arg ) {
2715 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2717 * wfMergeErrorArrays(
2718 * array( array( 'x' ) ),
2719 * array( array( 'x', '2' ) ),
2720 * array( array( 'x' ) ),
2721 * array( array( 'y') )
2725 * array( 'x', '2' ),
2730 function wfMergeErrorArrays( /*...*/ ) {
2731 $args = func_get_args();
2733 foreach ( $args as $errors ) {
2734 foreach ( $errors as $params ) {
2735 # FIXME: sometimes get nested arrays for $params,
2736 # which leads to E_NOTICEs
2737 $spec = implode( "\t", $params );
2738 $out[$spec] = $params;
2741 return array_values( $out );
2745 * parse_url() work-alike, but non-broken. Differences:
2747 * 1) Does not raise warnings on bad URLs (just returns false)
2748 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2749 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2751 * @param $url String: a URL to parse
2752 * @return Array: bits of the URL in an associative array, per PHP docs
2754 function wfParseUrl( $url ) {
2755 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2756 wfSuppressWarnings();
2757 $bits = parse_url( $url );
2758 wfRestoreWarnings();
2763 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2764 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2765 $bits['delimiter'] = '://';
2766 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2767 $bits['delimiter'] = ':';
2768 // parse_url detects for news: and mailto: the host part of an url as path
2769 // We have to correct this wrong detection
2770 if ( isset( $bits['path'] ) ) {
2771 $bits['host'] = $bits['path'];
2782 * Make a URL index, appropriate for the el_index field of externallinks.
2784 function wfMakeUrlIndex( $url ) {
2785 $bits = wfParseUrl( $url );
2787 // Reverse the labels in the hostname, convert to lower case
2788 // For emails reverse domainpart only
2789 if ( $bits['scheme'] == 'mailto' ) {
2790 $mailparts = explode( '@', $bits['host'], 2 );
2791 if ( count( $mailparts ) === 2 ) {
2792 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2794 // No domain specified, don't mangle it
2797 $reversedHost = $domainpart . '@' . $mailparts[0];
2799 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2801 // Add an extra dot to the end
2802 // Why? Is it in wrong place in mailto links?
2803 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2804 $reversedHost .= '.';
2806 // Reconstruct the pseudo-URL
2807 $prot = $bits['scheme'];
2808 $index = $prot . $bits['delimiter'] . $reversedHost;
2809 // Leave out user and password. Add the port, path, query and fragment
2810 if ( isset( $bits['port'] ) ) {
2811 $index .= ':' . $bits['port'];
2813 if ( isset( $bits['path'] ) ) {
2814 $index .= $bits['path'];
2818 if ( isset( $bits['query'] ) ) {
2819 $index .= '?' . $bits['query'];
2821 if ( isset( $bits['fragment'] ) ) {
2822 $index .= '#' . $bits['fragment'];
2828 * Do any deferred updates and clear the list
2830 * @param $commit String: set to 'commit' to commit after every update to
2831 * prevent lock contention
2833 function wfDoUpdates( $commit = '' ) {
2834 global $wgDeferredUpdateList;
2836 wfProfileIn( __METHOD__
);
2838 // No need to get master connections in case of empty updates array
2839 if ( !count( $wgDeferredUpdateList ) ) {
2840 wfProfileOut( __METHOD__
);
2844 $doCommit = $commit == 'commit';
2846 $dbw = wfGetDB( DB_MASTER
);
2849 foreach ( $wgDeferredUpdateList as $update ) {
2850 $update->doUpdate();
2852 if ( $doCommit && $dbw->trxLevel() ) {
2857 $wgDeferredUpdateList = array();
2858 wfProfileOut( __METHOD__
);
2862 * Convert an arbitrarily-long digit string from one numeric base
2863 * to another, optionally zero-padding to a minimum column width.
2865 * Supports base 2 through 36; digit values 10-36 are represented
2866 * as lowercase letters a-z. Input is case-insensitive.
2868 * @param $input String: of digits
2869 * @param $sourceBase Integer: 2-36
2870 * @param $destBase Integer: 2-36
2871 * @param $pad Integer: 1 or greater
2872 * @param $lowercase Boolean
2873 * @return String or false on invalid input
2875 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2876 $input = strval( $input );
2877 if( $sourceBase < 2 ||
2882 $sourceBase != intval( $sourceBase ) ||
2883 $destBase != intval( $destBase ) ||
2884 $pad != intval( $pad ) ||
2885 !is_string( $input ) ||
2889 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2890 $inDigits = array();
2893 // Decode and validate input string
2894 $input = strtolower( $input );
2895 for( $i = 0; $i < strlen( $input ); $i++
) {
2896 $n = strpos( $digitChars, $input{$i} );
2897 if( $n === false ||
$n > $sourceBase ) {
2903 // Iterate over the input, modulo-ing out an output digit
2904 // at a time until input is gone.
2905 while( count( $inDigits ) ) {
2907 $workDigits = array();
2910 foreach( $inDigits as $digit ) {
2911 $work *= $sourceBase;
2914 if( $work < $destBase ) {
2915 // Gonna need to pull another digit.
2916 if( count( $workDigits ) ) {
2917 // Avoid zero-padding; this lets us find
2918 // the end of the input very easily when
2919 // length drops to zero.
2923 // Finally! Actual division!
2924 $workDigits[] = intval( $work / $destBase );
2926 // Isn't it annoying that most programming languages
2927 // don't have a single divide-and-remainder operator,
2928 // even though the CPU implements it that way?
2929 $work = $work %
$destBase;
2933 // All that division leaves us with a remainder,
2934 // which is conveniently our next output digit.
2935 $outChars .= $digitChars[$work];
2938 $inDigits = $workDigits;
2941 while( strlen( $outChars ) < $pad ) {
2945 return strrev( $outChars );
2949 * Create an object with a given name and an array of construct parameters
2950 * @param $name String
2951 * @param $p Array: parameters
2953 function wfCreateObject( $name, $p ) {
2954 $p = array_values( $p );
2955 switch ( count( $p ) ) {
2959 return new $name( $p[0] );
2961 return new $name( $p[0], $p[1] );
2963 return new $name( $p[0], $p[1], $p[2] );
2965 return new $name( $p[0], $p[1], $p[2], $p[3] );
2967 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2969 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2971 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2975 function wfHttpOnlySafe() {
2976 global $wgHttpOnlyBlacklist;
2977 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
2981 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2982 foreach( $wgHttpOnlyBlacklist as $regex ) {
2983 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2993 * Initialise php session
2995 function wfSetupSession( $sessionId = false ) {
2996 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2997 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2998 if( $wgSessionsInMemcached ) {
2999 require_once( 'MemcachedSessions.php' );
3000 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3001 # Only set this if $wgSessionHandler isn't null and session.save_handler
3002 # hasn't already been set to the desired value (that causes errors)
3003 ini_set( 'session.save_handler', $wgSessionHandler );
3005 $httpOnlySafe = wfHttpOnlySafe();
3006 wfDebugLog( 'cookie',
3007 'session_set_cookie_params: "' . implode( '", "',
3013 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3014 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3015 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3017 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3018 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3020 session_cache_limiter( 'private, must-revalidate' );
3022 session_id( $sessionId );
3024 wfSuppressWarnings();
3026 wfRestoreWarnings();
3030 * Get an object from the precompiled serialized directory
3032 * @return Mixed: the variable on success, false on failure
3034 function wfGetPrecompiledData( $name ) {
3037 $file = "$IP/serialized/$name";
3038 if ( file_exists( $file ) ) {
3039 $blob = file_get_contents( $file );
3041 return unserialize( $blob );
3047 function wfGetCaller( $level = 2 ) {
3048 $backtrace = wfDebugBacktrace();
3049 if ( isset( $backtrace[$level] ) ) {
3050 return wfFormatStackFrame( $backtrace[$level] );
3052 $caller = 'unknown';
3058 * Return a string consisting of callers in the stack. Useful sometimes
3059 * for profiling specific points.
3061 * @param $limit The maximum depth of the stack frame to return, or false for
3064 function wfGetAllCallers( $limit = 3 ) {
3065 $trace = array_reverse( wfDebugBacktrace() );
3066 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3067 $limit = count( $trace ) - 1;
3069 $trace = array_slice( $trace, -$limit - 1, $limit );
3070 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3074 * Return a string representation of frame
3076 function wfFormatStackFrame( $frame ) {
3077 return isset( $frame['class'] ) ?
3078 $frame['class'] . '::' . $frame['function'] :
3085 function wfMemcKey( /*... */ ) {
3086 $args = func_get_args();
3087 $key = wfWikiID() . ':' . implode( ':', $args );
3088 $key = str_replace( ' ', '_', $key );
3093 * Get a cache key for a foreign DB
3095 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3096 $args = array_slice( func_get_args(), 2 );
3098 $key = "$db-$prefix:" . implode( ':', $args );
3100 $key = $db . ':' . implode( ':', $args );
3106 * Get an ASCII string identifying this wiki
3107 * This is used as a prefix in memcached keys
3109 function wfWikiID() {
3110 global $wgDBprefix, $wgDBname;
3111 if ( $wgDBprefix ) {
3112 return "$wgDBname-$wgDBprefix";
3119 * Split a wiki ID into DB name and table prefix
3121 function wfSplitWikiID( $wiki ) {
3122 $bits = explode( '-', $wiki, 2 );
3123 if ( count( $bits ) < 2 ) {
3130 * Get a Database object.
3131 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3132 * master (for write queries), DB_SLAVE for potentially lagged read
3133 * queries, or an integer >= 0 for a particular server.
3135 * @param $groups Mixed: query groups. An array of group names that this query
3136 * belongs to. May contain a single string if the query is only
3139 * @param $wiki String: the wiki ID, or false for the current wiki
3141 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3142 * will always return the same object, unless the underlying connection or load
3143 * balancer is manually destroyed.
3145 * @return DatabaseBase
3147 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3148 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3152 * Get a load balancer object.
3154 * @param $wiki String: wiki ID, or false for the current wiki
3155 * @return LoadBalancer
3157 function wfGetLB( $wiki = false ) {
3158 return wfGetLBFactory()->getMainLB( $wiki );
3162 * Get the load balancer factory object
3164 function &wfGetLBFactory() {
3165 return LBFactory
::singleton();
3170 * Shortcut for RepoGroup::singleton()->findFile()
3171 * @param $title String or Title object
3172 * @param $options Associative array of options:
3173 * time: requested time for an archived image, or false for the
3174 * current version. An image object will be returned which was
3175 * created at the specified time.
3177 * ignoreRedirect: If true, do not follow file redirects
3179 * private: If true, return restricted (deleted) files if the current
3180 * user is allowed to view them. Otherwise, such files will not
3183 * bypassCache: If true, do not use the process-local cache of File objects
3185 * @return File, or false if the file does not exist
3187 function wfFindFile( $title, $options = array() ) {
3188 return RepoGroup
::singleton()->findFile( $title, $options );
3192 * Get an object referring to a locally registered file.
3193 * Returns a valid placeholder object if the file does not exist.
3194 * @param $title Title or String
3195 * @return File, or null if passed an invalid Title
3197 function wfLocalFile( $title ) {
3198 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3202 * Should low-performance queries be disabled?
3206 function wfQueriesMustScale() {
3207 global $wgMiserMode;
3209 ||
( SiteStats
::pages() > 100000
3210 && SiteStats
::edits() > 1000000
3211 && SiteStats
::users() > 10000 );
3215 * Get the path to a specified script file, respecting file
3216 * extensions; this is a wrapper around $wgScriptExtension etc.
3218 * @param $script String: script filename, sans extension
3221 function wfScript( $script = 'index' ) {
3222 global $wgScriptPath, $wgScriptExtension;
3223 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3227 * Get the script URL.
3229 * @return script URL
3231 function wfGetScriptUrl() {
3232 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3234 # as it was called, minus the query string.
3236 # Some sites use Apache rewrite rules to handle subdomains,
3237 # and have PHP set up in a weird way that causes PHP_SELF
3238 # to contain the rewritten URL instead of the one that the
3239 # outside world sees.
3241 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3242 # provides containing the "before" URL.
3243 return $_SERVER['SCRIPT_NAME'];
3245 return $_SERVER['URL'];
3250 * Convenience function converts boolean values into "true"
3251 * or "false" (string) values
3253 * @param $value Boolean
3256 function wfBoolToStr( $value ) {
3257 return $value ?
'true' : 'false';
3261 * Load an extension messages file
3262 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3264 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3265 wfDeprecated( __FUNCTION__
);
3269 * Get a platform-independent path to the null file, e.g.
3274 function wfGetNull() {
3275 return wfIsWindows()
3281 * Displays a maxlag error
3283 * @param $host String: server that lags the most
3284 * @param $lag Integer: maxlag (actual)
3285 * @param $maxLag Integer: maxlag (requested)
3287 function wfMaxlagError( $host, $lag, $maxLag ) {
3288 global $wgShowHostnames;
3289 header( 'HTTP/1.1 503 Service Unavailable' );
3290 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3291 header( 'X-Database-Lag: ' . intval( $lag ) );
3292 header( 'Content-Type: text/plain' );
3293 if( $wgShowHostnames ) {
3294 echo "Waiting for $host: $lag seconds lagged\n";
3296 echo "Waiting for a database server: $lag seconds lagged\n";
3301 * Throws a warning that $function is deprecated
3302 * @param $function String
3305 function wfDeprecated( $function ) {
3306 static $functionsWarned = array();
3307 if ( !isset( $functionsWarned[$function] ) ) {
3308 $functionsWarned[$function] = true;
3309 wfWarn( "Use of $function is deprecated.", 2 );
3314 * Send a warning either to the debug log or in a PHP error depending on
3315 * $wgDevelopmentWarnings
3317 * @param $msg String: message to send
3318 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3319 * find the correct caller (1 = function calling wfWarn, ...)
3320 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3323 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3324 $callers = wfDebugBacktrace();
3325 if( isset( $callers[$callerOffset +
1] ) ){
3326 $callerfunc = $callers[$callerOffset +
1];
3327 $callerfile = $callers[$callerOffset];
3328 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3329 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3331 $file = '(internal function)';
3334 if( isset( $callerfunc['class'] ) ) {
3335 $func .= $callerfunc['class'] . '::';
3337 if( isset( $callerfunc['function'] ) ) {
3338 $func .= $callerfunc['function'];
3340 $msg .= " [Called from $func in $file]";
3343 global $wgDevelopmentWarnings;
3344 if ( $wgDevelopmentWarnings ) {
3345 trigger_error( $msg, $level );
3347 wfDebug( "$msg\n" );
3352 * Sleep until the worst slave's replication lag is less than or equal to
3353 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3354 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3355 * a no-op if there are no slaves.
3357 * Every time the function has to wait for a slave, it will print a message to
3358 * that effect (and then sleep for a little while), so it's probably not best
3359 * to use this outside maintenance scripts in its present form.
3361 * @param $maxLag Integer
3362 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3365 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3367 $lb = wfGetLB( $wiki );
3368 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3369 while( $lag > $maxLag ) {
3370 wfSuppressWarnings();
3371 $name = gethostbyaddr( $host );
3372 wfRestoreWarnings();
3373 if( $name !== false ) {
3376 print "Waiting for $host (lagged $lag seconds)...\n";
3378 list( $host, $lag ) = $lb->getMaxLag();
3384 * Output some plain text in command-line mode or in the installer (updaters.inc).
3385 * Do not use it in any other context, its behaviour is subject to change.
3387 function wfOut( $s ) {
3388 global $wgCommandLineMode;
3389 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3392 echo htmlspecialchars( $s );
3398 * Count down from $n to zero on the terminal, with a one-second pause
3399 * between showing each number. For use in command-line scripts.
3401 function wfCountDown( $n ) {
3402 for ( $i = $n; $i >= 0; $i-- ) {
3404 echo str_repeat( "\x08", strlen( $i +
1 ) );
3416 * Generate a random 32-character hexadecimal token.
3417 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3418 * characters before hashing.
3420 function wfGenerateToken( $salt = '' ) {
3421 $salt = serialize( $salt );
3422 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3426 * Replace all invalid characters with -
3427 * @param $name Mixed: filename to process
3429 function wfStripIllegalFilenameChars( $name ) {
3430 global $wgIllegalFileChars;
3431 $name = wfBaseName( $name );
3432 $name = preg_replace(
3433 "/[^" . Title
::legalChars() . "]" .
3434 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3443 * Insert array into another array after the specified *KEY*
3444 * @param $array Array: The array.
3445 * @param $insert Array: The array to insert.
3446 * @param $after Mixed: The key to insert after
3448 function wfArrayInsertAfter( $array, $insert, $after ) {
3449 // Find the offset of the element to insert after.
3450 $keys = array_keys( $array );
3451 $offsetByKey = array_flip( $keys );
3453 $offset = $offsetByKey[$after];
3455 // Insert at the specified offset
3456 $before = array_slice( $array, 0, $offset +
1, true );
3457 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3459 $output = $before +
$insert +
$after;
3464 /* Recursively converts the parameter (an object) to an array with the same data */
3465 function wfObjectToArray( $object, $recursive = true ) {
3467 foreach ( get_object_vars( $object ) as $key => $value ) {
3468 if ( is_object( $value ) && $recursive ) {
3469 $value = wfObjectToArray( $value );
3472 $array[$key] = $value;
3479 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3480 * @return Integer value memory was set to.
3482 function wfMemoryLimit() {
3483 global $wgMemoryLimit;
3484 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3485 if( $memlimit != -1 ) {
3486 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3487 if( $conflimit == -1 ) {
3488 wfDebug( "Removing PHP's memory limit\n" );
3489 wfSuppressWarnings();
3490 ini_set( 'memory_limit', $conflimit );
3491 wfRestoreWarnings();
3493 } elseif ( $conflimit > $memlimit ) {
3494 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3495 wfSuppressWarnings();
3496 ini_set( 'memory_limit', $conflimit );
3497 wfRestoreWarnings();
3505 * Converts shorthand byte notation to integer form
3506 * @param $string String
3509 function wfShorthandToInteger( $string = '' ) {
3510 $string = trim( $string );
3511 if( $string === '' ) {
3514 $last = $string[strlen( $string ) - 1];
3515 $val = intval( $string );
3520 // break intentionally missing
3524 // break intentionally missing
3534 * Get the normalised IETF language tag
3535 * @param $code String: The language code.
3536 * @return $langCode String: The language code which complying with BCP 47 standards.
3538 function wfBCP47( $code ) {
3539 $codeSegment = explode( '-', $code );
3540 foreach ( $codeSegment as $segNo => $seg ) {
3541 if ( count( $codeSegment ) > 0 ) {
3542 // ISO 3166 country code
3543 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3544 $codeBCP[$segNo] = strtoupper( $seg );
3545 // ISO 15924 script code
3546 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3547 $codeBCP[$segNo] = ucfirst( $seg );
3548 // Use lowercase for other cases
3550 $codeBCP[$segNo] = strtolower( $seg );
3553 // Use lowercase for single segment
3554 $codeBCP[$segNo] = strtolower( $seg );
3557 $langCode = implode( '-', $codeBCP );
3561 function wfArrayMap( $function, $input ) {
3562 $ret = array_map( $function, $input );
3563 foreach ( $ret as $key => $value ) {
3564 $taint = istainted( $input[$key] );
3566 taint( $ret[$key], $taint );