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 * 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, $wgCommandLineMode, $wgDebugToCommandLine;
309 static $recursion = 0;
311 static $cache = array(); // Cache of unoutputted messages
312 $text = wfDebugTimer() . $text;
314 if( $wgDebugToCommandLine && $wgCommandLineMode ) {
319 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
320 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
324 if ( ( $wgDebugComments ||
$wgShowDebug ) && !$logonly ) {
327 if ( !isset( $wgOut ) ) {
330 if ( !StubObject
::isRealObject( $wgOut ) ) {
339 // add the message and possible cached ones to the output
340 array_map( array( $wgOut, 'debug' ), $cache );
343 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
344 # Strip unprintables; they can switch terminal modes when binary data
345 # gets dumped, which is pretty annoying.
346 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
347 $text = $wgDebugLogPrefix . $text;
348 wfErrorLog( $text, $wgDebugLogFile );
352 function wfDebugTimer() {
353 global $wgDebugTimestamps;
354 if ( !$wgDebugTimestamps ) {
357 static $start = null;
359 if ( $start === null ) {
360 $start = microtime( true );
361 $prefix = "\n$start";
363 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
366 return $prefix . ' ';
370 * Send a line giving PHP memory usage.
371 * @param $exact Bool: print exact values instead of kilobytes (default: false)
373 function wfDebugMem( $exact = false ) {
374 $mem = memory_get_usage();
376 $mem = floor( $mem / 1024 ) . ' kilobytes';
380 wfDebug( "Memory usage: $mem\n" );
384 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
385 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
387 * @param $logGroup String
388 * @param $text String
389 * @param $public Bool: whether to log the event in the public log if no private
390 * log file is specified, (default true)
392 function wfDebugLog( $logGroup, $text, $public = true ) {
393 global $wgDebugLogGroups, $wgShowHostnames;
394 $text = trim( $text ) . "\n";
395 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
396 $time = wfTimestamp( TS_DB
);
398 if ( $wgShowHostnames ) {
399 $host = wfHostname();
403 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
404 } elseif ( $public === true ) {
405 wfDebug( $text, true );
410 * Log for database errors
411 * @param $text String: database error message.
413 function wfLogDBError( $text ) {
414 global $wgDBerrorLog, $wgDBname;
415 if ( $wgDBerrorLog ) {
416 $host = trim(`hostname`
);
417 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
418 wfErrorLog( $text, $wgDBerrorLog );
423 * Log to a file without getting "file size exceeded" signals.
425 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
426 * send lines to the specified port, prefixed by the specified prefix and a space.
428 function wfErrorLog( $text, $file ) {
429 if ( substr( $file, 0, 4 ) == 'udp:' ) {
430 # Needs the sockets extension
431 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
432 // IPv6 bracketed host
434 $port = intval( $m[3] );
435 $prefix = isset( $m[4] ) ?
$m[4] : false;
437 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
439 if ( !IP
::isIPv4( $host ) ) {
440 $host = gethostbyname( $host );
442 $port = intval( $m[3] );
443 $prefix = isset( $m[4] ) ?
$m[4] : false;
446 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
448 // Clean it up for the multiplexer
449 if ( strval( $prefix ) !== '' ) {
450 $text = preg_replace( '/^/m', $prefix . ' ', $text );
451 if ( substr( $text, -1 ) != "\n" ) {
456 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
460 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
461 socket_close( $sock );
463 wfSuppressWarnings();
464 $exists = file_exists( $file );
465 $size = $exists ?
filesize( $file ) : false;
466 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
467 error_log( $text, 3, $file );
476 function wfLogProfilingData() {
477 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
478 global $wgProfiler, $wgProfileLimit, $wgUser;
479 # Profiling must actually be enabled...
480 if( is_null( $wgProfiler ) ) {
483 # Get total page request time
485 $elapsed = $now - $wgRequestTime;
486 # Only show pages that longer than $wgProfileLimit time (default is 0)
487 if( $elapsed <= $wgProfileLimit ) {
490 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
492 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
493 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
495 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
496 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
498 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
499 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
502 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
504 // Don't unstub $wgUser at this late stage just for statistics purposes
505 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
506 if( $wgUser->mDataLoaded
&& $wgUser->isAnon() ) {
509 $log = sprintf( "%s\t%04.3f\t%s\n",
510 gmdate( 'YmdHis' ), $elapsed,
511 urldecode( $wgRequest->getRequestURL() . $forward ) );
512 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' ||
$wgDebugRawPage ) ) {
513 wfErrorLog( $log . $prof, $wgDebugLogFile );
518 * Check if the wiki read-only lock file is present. This can be used to lock
519 * off editing functions, but doesn't guarantee that the database will not be
523 function wfReadOnly() {
524 global $wgReadOnlyFile, $wgReadOnly;
526 if ( !is_null( $wgReadOnly ) ) {
527 return (bool)$wgReadOnly;
529 if ( $wgReadOnlyFile == '' ) {
532 // Set $wgReadOnly for faster access next time
533 if ( is_file( $wgReadOnlyFile ) ) {
534 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
538 return (bool)$wgReadOnly;
541 function wfReadOnlyReason() {
548 * Return a Language object from $langcode
549 * @param $langcode Mixed: either:
550 * - a Language object
551 * - code of the language to get the message for, if it is
552 * a valid code create a language for that language, if
553 * it is a string but not a valid code then make a basic
555 * - a boolean: if it's false then use the current users
556 * language (as a fallback for the old parameter
557 * functionality), or if it is true then use the wikis
558 * @return Language object
560 function wfGetLangObj( $langcode = false ) {
561 # Identify which language to get or create a language object for.
562 # Using is_object here due to Stub objects.
563 if( is_object( $langcode ) ) {
564 # Great, we already have the object (hopefully)!
568 global $wgContLang, $wgLanguageCode;
569 if( $langcode === true ||
$langcode === $wgLanguageCode ) {
570 # $langcode is the language code of the wikis content language object.
571 # or it is a boolean and value is true
576 if( $langcode === false ||
$langcode === $wgLang->getCode() ) {
577 # $langcode is the language code of user language object.
578 # or it was a boolean and value is false
582 $validCodes = array_keys( Language
::getLanguageNames() );
583 if( in_array( $langcode, $validCodes ) ) {
584 # $langcode corresponds to a valid language.
585 return Language
::factory( $langcode );
588 # $langcode is a string, but not a valid language code; use content language.
589 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
594 * Use this instead of $wgContLang, when working with user interface.
595 * User interface is currently hard coded according to wiki content language
596 * in many ways, especially regarding to text direction. There is lots stuff
597 * to fix, hence this function to keep the old behaviour unless the global
598 * $wgBetterDirectionality is enabled (or removed when everything works).
600 function wfUILang() {
601 global $wgBetterDirectionality;
602 return wfGetLangObj( !$wgBetterDirectionality );
606 * This is the new function for getting translated interface messages.
607 * See the Message class for documentation how to use them.
608 * The intention is that this function replaces all old wfMsg* functions.
609 * @param $key \string Message key.
610 * Varargs: normal message parameters.
611 * @return \type{Message}
614 function wfMessage( $key /*...*/) {
615 $params = func_get_args();
616 array_shift( $params );
617 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
618 $params = $params[0];
620 return new Message( $key, $params );
624 * Get a message from anywhere, for the current user language.
626 * Use wfMsgForContent() instead if the message should NOT
627 * change depending on the user preferences.
629 * @param $key String: lookup key for the message, usually
630 * defined in languages/Language.php
632 * This function also takes extra optional parameters (not
633 * shown in the function definition), which can be used to
634 * insert variable text into the predefined message.
636 function wfMsg( $key ) {
637 $args = func_get_args();
638 array_shift( $args );
639 return wfMsgReal( $key, $args, true );
643 * Same as above except doesn't transform the message
645 function wfMsgNoTrans( $key ) {
646 $args = func_get_args();
647 array_shift( $args );
648 return wfMsgReal( $key, $args, true, false, false );
652 * Get a message from anywhere, for the current global language
653 * set with $wgLanguageCode.
655 * Use this if the message should NOT change dependent on the
656 * language set in the user's preferences. This is the case for
657 * most text written into logs, as well as link targets (such as
658 * the name of the copyright policy page). Link titles, on the
659 * other hand, should be shown in the UI language.
661 * Note that MediaWiki allows users to change the user interface
662 * language in their preferences, but a single installation
663 * typically only contains content in one language.
665 * Be wary of this distinction: If you use wfMsg() where you should
666 * use wfMsgForContent(), a user of the software may have to
667 * customize potentially hundreds of messages in
668 * order to, e.g., fix a link in every possible language.
670 * @param $key String: lookup key for the message, usually
671 * defined in languages/Language.php
673 function wfMsgForContent( $key ) {
674 global $wgForceUIMsgAsContentMsg;
675 $args = func_get_args();
676 array_shift( $args );
678 if( is_array( $wgForceUIMsgAsContentMsg ) &&
679 in_array( $key, $wgForceUIMsgAsContentMsg ) )
683 return wfMsgReal( $key, $args, true, $forcontent );
687 * Same as above except doesn't transform the message
689 function wfMsgForContentNoTrans( $key ) {
690 global $wgForceUIMsgAsContentMsg;
691 $args = func_get_args();
692 array_shift( $args );
694 if( is_array( $wgForceUIMsgAsContentMsg ) &&
695 in_array( $key, $wgForceUIMsgAsContentMsg ) )
699 return wfMsgReal( $key, $args, true, $forcontent, false );
703 * Get a message from the language file, for the UI elements
705 function wfMsgNoDB( $key ) {
706 $args = func_get_args();
707 array_shift( $args );
708 return wfMsgReal( $key, $args, false );
712 * Get a message from the language file, for the content
714 function wfMsgNoDBForContent( $key ) {
715 global $wgForceUIMsgAsContentMsg;
716 $args = func_get_args();
717 array_shift( $args );
719 if( is_array( $wgForceUIMsgAsContentMsg ) &&
720 in_array( $key, $wgForceUIMsgAsContentMsg ) )
724 return wfMsgReal( $key, $args, false, $forcontent );
729 * Really get a message
730 * @param $key String: key to get.
732 * @param $useDB Boolean
733 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
734 * @param $transform Boolean: Whether or not to transform the message.
735 * @return String: the requested message.
737 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
738 wfProfileIn( __METHOD__
);
739 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
740 $message = wfMsgReplaceArgs( $message, $args );
741 wfProfileOut( __METHOD__
);
746 * This function provides the message source for messages to be edited which are *not* stored in the database.
747 * @param $key String:
749 function wfMsgWeirdKey( $key ) {
750 $source = wfMsgGetKey( $key, false, true, false );
751 if ( wfEmptyMsg( $key, $source ) ) {
759 * Fetch a message string value, but don't replace any keys yet.
762 * @param $langCode String: Code of the language to get the message for, or
763 * behaves as a content language switch if it is a boolean.
764 * @param $transform Boolean: whether to parse magic words, etc.
767 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
768 global $wgMessageCache;
770 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
772 if ( !is_object( $wgMessageCache ) ) {
773 throw new MWException( 'Trying to get message before message cache is initialised' );
776 $message = $wgMessageCache->get( $key, $useDB, $langCode );
777 if( $message === false ) {
778 $message = '<' . htmlspecialchars( $key ) . '>';
779 } elseif ( $transform ) {
780 $message = $wgMessageCache->transform( $message );
786 * Replace message parameter keys on the given formatted output.
788 * @param $message String
793 function wfMsgReplaceArgs( $message, $args ) {
794 # Fix windows line-endings
795 # Some messages are split with explode("\n", $msg)
796 $message = str_replace( "\r", '', $message );
799 if ( count( $args ) ) {
800 if ( is_array( $args[0] ) ) {
801 $args = array_values( $args[0] );
803 $replacementKeys = array();
804 foreach( $args as $n => $param ) {
805 $replacementKeys['$' . ( $n +
1 )] = $param;
807 $message = strtr( $message, $replacementKeys );
814 * Return an HTML-escaped version of a message.
815 * Parameter replacements, if any, are done *after* the HTML-escaping,
816 * so parameters may contain HTML (eg links or form controls). Be sure
817 * to pre-escape them if you really do want plaintext, or just wrap
818 * the whole thing in htmlspecialchars().
821 * @param string ... parameters
824 function wfMsgHtml( $key ) {
825 $args = func_get_args();
826 array_shift( $args );
827 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
831 * Return an HTML version of message
832 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
833 * so parameters may contain HTML (eg links or form controls). Be sure
834 * to pre-escape them if you really do want plaintext, or just wrap
835 * the whole thing in htmlspecialchars().
838 * @param string ... parameters
841 function wfMsgWikiHtml( $key ) {
843 $args = func_get_args();
844 array_shift( $args );
845 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
849 * Returns message in the requested format
850 * @param $key String: key of the message
851 * @param $options Array: processing rules. Can take the following options:
852 * <i>parse</i>: parses wikitext to HTML
853 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
854 * p's added by parser or tidy
855 * <i>escape</i>: filters message through htmlspecialchars
856 * <i>escapenoentities</i>: same, but allows entity references like   through
857 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
858 * <i>parsemag</i>: transform the message using magic phrases
859 * <i>content</i>: fetch message for content language instead of interface
860 * Also can accept a single associative argument, of the form 'language' => 'xx':
861 * <i>language</i>: Language object or language code to fetch message for
862 * (overriden by <i>content</i>), its behaviour with parse, parseinline
863 * and parsemag is undefined.
864 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
866 function wfMsgExt( $key, $options ) {
869 $args = func_get_args();
870 array_shift( $args );
871 array_shift( $args );
872 $options = (array)$options;
874 foreach( $options as $arrayKey => $option ) {
875 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
876 # An unknown index, neither numeric nor "language"
877 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
878 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
879 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
880 'replaceafter', 'parsemag', 'content' ) ) ) {
881 # A numeric index with unknown value
882 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
886 if( in_array( 'content', $options, true ) ) {
889 } elseif( array_key_exists( 'language', $options ) ) {
891 $langCode = wfGetLangObj( $options['language'] );
897 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
899 if( !in_array( 'replaceafter', $options, true ) ) {
900 $string = wfMsgReplaceArgs( $string, $args );
903 if( in_array( 'parse', $options, true ) ) {
904 $string = $wgOut->parse( $string, true, !$forContent );
905 } elseif ( in_array( 'parseinline', $options, true ) ) {
906 $string = $wgOut->parse( $string, true, !$forContent );
908 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
911 } elseif ( in_array( 'parsemag', $options, true ) ) {
912 global $wgMessageCache;
913 if ( isset( $wgMessageCache ) ) {
914 $string = $wgMessageCache->transform( $string,
916 is_object( $langCode ) ?
$langCode : null );
920 if ( in_array( 'escape', $options, true ) ) {
921 $string = htmlspecialchars ( $string );
922 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
923 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
926 if( in_array( 'replaceafter', $options, true ) ) {
927 $string = wfMsgReplaceArgs( $string, $args );
935 * Just like exit() but makes a note of it.
936 * Commits open transactions except if the error parameter is set
938 * @deprecated Please return control to the caller or throw an exception. Will
939 * be removed in 1.19.
941 function wfAbruptExit( $error = false ) {
942 static $called = false;
948 wfDeprecated( __FUNCTION__
);
949 $bt = wfDebugBacktrace();
951 for( $i = 0; $i < count( $bt ); $i++
) {
952 $file = isset( $bt[$i]['file'] ) ?
$bt[$i]['file'] : 'unknown';
953 $line = isset( $bt[$i]['line'] ) ?
$bt[$i]['line'] : 'unknown';
954 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
957 wfDebug( "WARNING: Abrupt exit\n" );
960 wfLogProfilingData();
963 wfGetLB()->closeAll();
969 * @deprecated Please return control the caller or throw an exception. Will
970 * be removed in 1.19.
972 function wfErrorExit() {
973 wfDeprecated( __FUNCTION__
);
974 wfAbruptExit( true );
978 * Print a simple message and die, returning nonzero to the shell if any.
979 * Plain die() fails to return nonzero to the shell if you pass a string.
982 function wfDie( $msg = '' ) {
988 * Throw a debugging exception. This function previously once exited the process,
989 * but now throws an exception instead, with similar results.
991 * @param $msg String: message shown when dieing.
993 function wfDebugDieBacktrace( $msg = '' ) {
994 throw new MWException( $msg );
998 * Fetch server name for use in error reporting etc.
999 * Use real server name if available, so we know which machine
1000 * in a server farm generated the current page.
1003 function wfHostname() {
1005 if ( is_null( $host ) ) {
1006 if ( function_exists( 'posix_uname' ) ) {
1007 // This function not present on Windows
1008 $uname = @posix_uname
();
1012 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1013 $host = $uname['nodename'];
1014 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1015 # Windows computer name
1016 $host = getenv( 'COMPUTERNAME' );
1018 # This may be a virtual server.
1019 $host = $_SERVER['SERVER_NAME'];
1026 * Returns a HTML comment with the elapsed time since request.
1027 * This method has no side effects.
1030 function wfReportTime() {
1031 global $wgRequestTime, $wgShowHostnames;
1034 $elapsed = $now - $wgRequestTime;
1036 return $wgShowHostnames
1037 ?
sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1038 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1042 * Safety wrapper for debug_backtrace().
1044 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1045 * murky circumstances, which may be triggered in part by stub objects
1046 * or other fancy talkin'.
1048 * Will return an empty array if Zend Optimizer is detected or if
1049 * debug_backtrace is disabled, otherwise the output from
1050 * debug_backtrace() (trimmed).
1052 * @return array of backtrace information
1054 function wfDebugBacktrace() {
1055 static $disabled = null;
1057 if( extension_loaded( 'Zend Optimizer' ) ) {
1058 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1062 if ( is_null( $disabled ) ) {
1064 $functions = explode( ',', ini_get( 'disable_functions' ) );
1065 $functions = array_map( 'trim', $functions );
1066 $functions = array_map( 'strtolower', $functions );
1067 if ( in_array( 'debug_backtrace', $functions ) ) {
1068 wfDebug( "debug_backtrace is in disabled_functions\n" );
1076 return array_slice( debug_backtrace(), 1 );
1079 function wfBacktrace() {
1080 global $wgCommandLineMode;
1082 if ( $wgCommandLineMode ) {
1087 $backtrace = wfDebugBacktrace();
1088 foreach( $backtrace as $call ) {
1089 if( isset( $call['file'] ) ) {
1090 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1091 $file = $f[count( $f ) - 1];
1095 if( isset( $call['line'] ) ) {
1096 $line = $call['line'];
1100 if ( $wgCommandLineMode ) {
1101 $msg .= "$file line $line calls ";
1103 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1105 if( !empty( $call['class'] ) ) {
1106 $msg .= $call['class'] . '::';
1108 $msg .= $call['function'] . '()';
1110 if ( $wgCommandLineMode ) {
1116 if ( $wgCommandLineMode ) {
1126 /* Some generic result counters, pulled out of SearchEngine */
1132 function wfShowingResults( $offset, $limit ) {
1136 array( 'parseinline' ),
1137 $wgLang->formatNum( $limit ),
1138 $wgLang->formatNum( $offset +
1 )
1145 function wfShowingResultsNum( $offset, $limit, $num ) {
1148 'showingresultsnum',
1149 array( 'parseinline' ),
1150 $wgLang->formatNum( $limit ),
1151 $wgLang->formatNum( $offset +
1 ),
1152 $wgLang->formatNum( $num )
1157 * Generate (prev x| next x) (20|50|100...) type links for paging
1158 * @param $offset String
1159 * @param $limit Integer
1160 * @param $link String
1161 * @param $query String: optional URL query parameter string
1162 * @param $atend Bool: optional param for specified if this is the last page
1164 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1166 $fmtLimit = $wgLang->formatNum( $limit );
1167 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1168 # Get prev/next link display text
1169 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1170 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1171 # Get prev/next link title text
1172 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1173 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1174 # Fetch the title object
1175 if( is_object( $link ) ) {
1178 $title = Title
::newFromText( $link );
1179 if( is_null( $title ) ) {
1183 # Make 'previous' link
1184 if( 0 != $offset ) {
1185 $po = $offset - $limit;
1186 $po = max( $po, 0 );
1187 $q = "limit={$limit}&offset={$po}";
1188 if( $query != '' ) {
1191 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1196 $no = $offset +
$limit;
1197 $q = "limit={$limit}&offset={$no}";
1198 if( $query != '' ) {
1204 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1206 # Make links to set number of items per page
1207 $nums = $wgLang->pipeList( array(
1208 wfNumLink( $offset, 20, $title, $query ),
1209 wfNumLink( $offset, 50, $title, $query ),
1210 wfNumLink( $offset, 100, $title, $query ),
1211 wfNumLink( $offset, 250, $title, $query ),
1212 wfNumLink( $offset, 500, $title, $query )
1214 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1218 * Generate links for (20|50|100...) items-per-page links
1219 * @param $offset String
1220 * @param $limit Integer
1221 * @param $title Title
1222 * @param $query String: optional URL query parameter string
1224 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1226 if( $query == '' ) {
1231 $q .= "limit={$limit}&offset={$offset}";
1232 $fmtLimit = $wgLang->formatNum( $limit );
1233 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1234 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1240 * @todo FIXME: we may want to blacklist some broken browsers
1242 * @return bool Whereas client accept gzip compression
1244 function wfClientAcceptsGzip() {
1245 static $result = null;
1246 if ( $result === null ) {
1248 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1249 # FIXME: we may want to blacklist some broken browsers
1252 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1253 $_SERVER['HTTP_ACCEPT_ENCODING'],
1257 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1261 wfDebug( " accepts gzip\n" );
1270 * Obtain the offset and limit values from the request string;
1271 * used in special pages
1273 * @param $deflimit Default limit if none supplied
1274 * @param $optionname Name of a user preference to check against
1278 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1280 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1284 * Escapes the given text so that it may be output using addWikiText()
1285 * without any linking, formatting, etc. making its way through. This
1286 * is achieved by substituting certain characters with HTML entities.
1287 * As required by the callers, <nowiki> is not used. It currently does
1288 * not filter out characters which have special meaning only at the
1289 * start of a line, such as "*".
1291 * @param $text String: text to be escaped
1293 function wfEscapeWikiText( $text ) {
1294 $text = str_replace(
1295 array( '[', '|', ']', '\'', 'ISBN ',
1296 'RFC ', '://', "\n=", '{{', '}}' ),
1297 array( '[', '|', ']', ''', 'ISBN ',
1298 'RFC ', '://', "\n=", '{{', '}}' ),
1299 htmlspecialchars( $text )
1307 function wfQuotedPrintable( $string, $charset = '' ) {
1308 # Probably incomplete; see RFC 2045
1309 if( empty( $charset ) ) {
1310 global $wgInputEncoding;
1311 $charset = $wgInputEncoding;
1313 $charset = strtoupper( $charset );
1314 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1316 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1317 $replace = $illegal . '\t ?_';
1318 if( !preg_match( "/[$illegal]/", $string ) ) {
1321 $out = "=?$charset?Q?";
1322 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1333 return microtime( true );
1337 * Sets dest to source and returns the original value of dest
1338 * If source is NULL, it just returns the value, it doesn't set the variable
1340 function wfSetVar( &$dest, $source ) {
1342 if ( !is_null( $source ) ) {
1349 * As for wfSetVar except setting a bit
1351 function wfSetBit( &$dest, $bit, $state = true ) {
1352 $temp = (bool)( $dest & $bit );
1353 if ( !is_null( $state ) ) {
1364 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1365 * "days=7&limit=100". Options in the first array override options in the second.
1366 * Options set to "" will not be output.
1368 function wfArrayToCGI( $array1, $array2 = null ) {
1369 if ( !is_null( $array2 ) ) {
1370 $array1 = $array1 +
$array2;
1374 foreach ( $array1 as $key => $value ) {
1375 if ( $value !== '' ) {
1379 if ( is_array( $value ) ) {
1381 foreach ( $value as $v ) {
1382 $cgi .= ( $firstTime ?
'' : '&') .
1383 urlencode( $key . '[]' ) . '=' .
1388 if ( is_object( $value ) ) {
1389 $value = $value->__toString();
1391 $cgi .= urlencode( $key ) . '=' .
1392 urlencode( $value );
1400 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1401 * its argument and returns the same string in array form. This allows compa-
1402 * tibility with legacy functions that accept raw query strings instead of nice
1403 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1404 * valid query strings, or it will explode.
1406 * @param $query String: query string
1407 * @return array Array version of input
1409 function wfCgiToArray( $query ) {
1410 if( isset( $query[0] ) && $query[0] == '?' ) {
1411 $query = substr( $query, 1 );
1413 $bits = explode( '&', $query );
1415 foreach( $bits as $bit ) {
1419 list( $key, $value ) = explode( '=', $bit );
1420 $key = urldecode( $key );
1421 $value = urldecode( $value );
1422 $ret[$key] = $value;
1428 * Append a query string to an existing URL, which may or may not already
1429 * have query string parameters already. If so, they will be combined.
1431 * @param $url String
1432 * @param $query Mixed: string or associative array
1435 function wfAppendQuery( $url, $query ) {
1436 if ( is_array( $query ) ) {
1437 $query = wfArrayToCGI( $query );
1439 if( $query != '' ) {
1440 if( false === strpos( $url, '?' ) ) {
1451 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1452 * and $wgProto are correct.
1454 * @todo this won't work with current-path-relative URLs
1455 * like "subdir/foo.html", etc.
1457 * @param $url String: either fully-qualified or a local path + query
1458 * @return string Fully-qualified URL
1460 function wfExpandUrl( $url ) {
1461 if( substr( $url, 0, 2 ) == '//' ) {
1463 return $wgProto . ':' . $url;
1464 } elseif( substr( $url, 0, 1 ) == '/' ) {
1466 return $wgServer . $url;
1473 * Windows-compatible version of escapeshellarg()
1474 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1475 * function puts single quotes in regardless of OS.
1477 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1478 * earlier distro releases of PHP)
1480 function wfEscapeShellArg( ) {
1481 wfInitShellLocale();
1483 $args = func_get_args();
1486 foreach ( $args as $arg ) {
1493 if ( wfIsWindows() ) {
1494 // Escaping for an MSVC-style command line parser
1495 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1496 // Double the backslashes before any double quotes. Escape the double quotes.
1497 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1500 foreach ( $tokens as $token ) {
1501 if ( $iteration %
2 == 1 ) {
1502 // Delimiter, a double quote preceded by zero or more slashes
1503 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1504 } elseif ( $iteration %
4 == 2 ) {
1505 // ^ in $token will be outside quotes, need to be escaped
1506 $arg .= str_replace( '^', '^^', $token );
1507 } else { // $iteration % 4 == 0
1508 // ^ in $token will appear inside double quotes, so leave as is
1513 // Double the backslashes before the end of the string, because
1514 // we will soon add a quote
1516 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1517 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1520 // Add surrounding quotes
1521 $retVal .= '"' . $arg . '"';
1523 $retVal .= escapeshellarg( $arg );
1530 * wfMerge attempts to merge differences between three texts.
1531 * Returns true for a clean merge and false for failure or a conflict.
1533 function wfMerge( $old, $mine, $yours, &$result ) {
1536 # This check may also protect against code injection in
1537 # case of broken installations.
1538 wfSuppressWarnings();
1539 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1540 wfRestoreWarnings();
1543 wfDebug( "diff3 not found\n" );
1547 # Make temporary files
1549 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1550 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1551 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1553 fwrite( $oldtextFile, $old );
1554 fclose( $oldtextFile );
1555 fwrite( $mytextFile, $mine );
1556 fclose( $mytextFile );
1557 fwrite( $yourtextFile, $yours );
1558 fclose( $yourtextFile );
1560 # Check for a conflict
1561 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1562 wfEscapeShellArg( $mytextName ) . ' ' .
1563 wfEscapeShellArg( $oldtextName ) . ' ' .
1564 wfEscapeShellArg( $yourtextName );
1565 $handle = popen( $cmd, 'r' );
1567 if( fgets( $handle, 1024 ) ) {
1575 $cmd = $wgDiff3 . ' -a -e --merge ' .
1576 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1577 $handle = popen( $cmd, 'r' );
1580 $data = fread( $handle, 8192 );
1581 if ( strlen( $data ) == 0 ) {
1587 unlink( $mytextName );
1588 unlink( $oldtextName );
1589 unlink( $yourtextName );
1591 if ( $result === '' && $old !== '' && !$conflict ) {
1592 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1599 * Returns unified plain-text diff of two texts.
1600 * Useful for machine processing of diffs.
1601 * @param $before String: the text before the changes.
1602 * @param $after String: the text after the changes.
1603 * @param $params String: command-line options for the diff command.
1604 * @return String: unified diff of $before and $after
1606 function wfDiff( $before, $after, $params = '-u' ) {
1607 if ( $before == $after ) {
1612 wfSuppressWarnings();
1613 $haveDiff = $wgDiff && file_exists( $wgDiff );
1614 wfRestoreWarnings();
1616 # This check may also protect against code injection in
1617 # case of broken installations.
1619 wfDebug( "diff executable not found\n" );
1620 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1621 $format = new UnifiedDiffFormatter();
1622 return $format->format( $diffs );
1625 # Make temporary files
1627 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1628 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1630 fwrite( $oldtextFile, $before );
1631 fclose( $oldtextFile );
1632 fwrite( $newtextFile, $after );
1633 fclose( $newtextFile );
1635 // Get the diff of the two files
1636 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1638 $h = popen( $cmd, 'r' );
1643 $data = fread( $h, 8192 );
1644 if ( strlen( $data ) == 0 ) {
1652 unlink( $oldtextName );
1653 unlink( $newtextName );
1655 // Kill the --- and +++ lines. They're not useful.
1656 $diff_lines = explode( "\n", $diff );
1657 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1658 unset( $diff_lines[0] );
1660 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1661 unset( $diff_lines[1] );
1664 $diff = implode( "\n", $diff_lines );
1670 * A wrapper around the PHP function var_export().
1671 * Either print it or add it to the regular output ($wgOut).
1673 * @param $var A PHP variable to dump.
1675 function wfVarDump( $var ) {
1677 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1678 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1681 $wgOut->addHTML( $s );
1686 * Provide a simple HTTP error.
1688 function wfHttpError( $code, $label, $desc ) {
1691 header( "HTTP/1.0 $code $label" );
1692 header( "Status: $code $label" );
1693 $wgOut->sendCacheControl();
1695 header( 'Content-type: text/html; charset=utf-8' );
1696 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1697 '<html><head><title>' .
1698 htmlspecialchars( $label ) .
1699 '</title></head><body><h1>' .
1700 htmlspecialchars( $label ) .
1702 nl2br( htmlspecialchars( $desc ) ) .
1703 "</p></body></html>\n";
1707 * Clear away any user-level output buffers, discarding contents.
1709 * Suitable for 'starting afresh', for instance when streaming
1710 * relatively large amounts of data without buffering, or wanting to
1711 * output image files without ob_gzhandler's compression.
1713 * The optional $resetGzipEncoding parameter controls suppression of
1714 * the Content-Encoding header sent by ob_gzhandler; by default it
1715 * is left. See comments for wfClearOutputBuffers() for why it would
1718 * Note that some PHP configuration options may add output buffer
1719 * layers which cannot be removed; these are left in place.
1721 * @param $resetGzipEncoding Bool
1723 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1724 if( $resetGzipEncoding ) {
1725 // Suppress Content-Encoding and Content-Length
1726 // headers from 1.10+s wfOutputHandler
1727 global $wgDisableOutputCompression;
1728 $wgDisableOutputCompression = true;
1730 while( $status = ob_get_status() ) {
1731 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1732 // Probably from zlib.output_compression or other
1733 // PHP-internal setting which can't be removed.
1735 // Give up, and hope the result doesn't break
1739 if( !ob_end_clean() ) {
1740 // Could not remove output buffer handler; abort now
1741 // to avoid getting in some kind of infinite loop.
1744 if( $resetGzipEncoding ) {
1745 if( $status['name'] == 'ob_gzhandler' ) {
1746 // Reset the 'Content-Encoding' field set by this handler
1747 // so we can start fresh.
1748 header( 'Content-Encoding:' );
1756 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1758 * Clear away output buffers, but keep the Content-Encoding header
1759 * produced by ob_gzhandler, if any.
1761 * This should be used for HTTP 304 responses, where you need to
1762 * preserve the Content-Encoding header of the real result, but
1763 * also need to suppress the output of ob_gzhandler to keep to spec
1764 * and avoid breaking Firefox in rare cases where the headers and
1765 * body are broken over two packets.
1767 function wfClearOutputBuffers() {
1768 wfResetOutputBuffers( false );
1772 * Converts an Accept-* header into an array mapping string values to quality
1775 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1776 # No arg means accept anything (per HTTP spec)
1778 return array( $def => 1.0 );
1783 $parts = explode( ',', $accept );
1785 foreach( $parts as $part ) {
1786 # FIXME: doesn't deal with params like 'text/html; level=1'
1787 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1789 if( !isset( $qpart ) ) {
1790 $prefs[$value] = 1.0;
1791 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1792 $prefs[$value] = floatval( $match[1] );
1800 * Checks if a given MIME type matches any of the keys in the given
1801 * array. Basic wildcards are accepted in the array keys.
1803 * Returns the matching MIME type (or wildcard) if a match, otherwise
1806 * @param $type String
1807 * @param $avail Array
1811 function mimeTypeMatch( $type, $avail ) {
1812 if( array_key_exists( $type, $avail ) ) {
1815 $parts = explode( '/', $type );
1816 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1817 return $parts[0] . '/*';
1818 } elseif( array_key_exists( '*/*', $avail ) ) {
1827 * Returns the 'best' match between a client's requested internet media types
1828 * and the server's list of available types. Each list should be an associative
1829 * array of type to preference (preference is a float between 0.0 and 1.0).
1830 * Wildcards in the types are acceptable.
1832 * @param $cprefs Array: client's acceptable type list
1833 * @param $sprefs Array: server's offered types
1836 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1837 * XXX: generalize to negotiate other stuff
1839 function wfNegotiateType( $cprefs, $sprefs ) {
1842 foreach( array_keys($sprefs) as $type ) {
1843 $parts = explode( '/', $type );
1844 if( $parts[1] != '*' ) {
1845 $ckey = mimeTypeMatch( $type, $cprefs );
1847 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1852 foreach( array_keys( $cprefs ) as $type ) {
1853 $parts = explode( '/', $type );
1854 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1855 $skey = mimeTypeMatch( $type, $sprefs );
1857 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1865 foreach( array_keys( $combine ) as $type ) {
1866 if( $combine[$type] > $bestq ) {
1868 $bestq = $combine[$type];
1877 * Returns an array where the values in the first array are replaced by the
1878 * values in the second array with the corresponding keys
1882 function wfArrayLookup( $a, $b ) {
1883 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1887 * Convenience function; returns MediaWiki timestamp for the present time.
1890 function wfTimestampNow() {
1892 return wfTimestamp( TS_MW
, time() );
1896 * Reference-counted warning suppression
1898 function wfSuppressWarnings( $end = false ) {
1899 static $suppressCount = 0;
1900 static $originalLevel = false;
1903 if ( $suppressCount ) {
1905 if ( !$suppressCount ) {
1906 error_reporting( $originalLevel );
1910 if ( !$suppressCount ) {
1911 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
) );
1918 * Restore error level to previous value
1920 function wfRestoreWarnings() {
1921 wfSuppressWarnings( true );
1924 # Autodetect, convert and provide timestamps of various types
1927 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1929 define( 'TS_UNIX', 0 );
1932 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1934 define( 'TS_MW', 1 );
1937 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1939 define( 'TS_DB', 2 );
1942 * RFC 2822 format, for E-mail and HTTP headers
1944 define( 'TS_RFC2822', 3 );
1947 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1949 * This is used by Special:Export
1951 define( 'TS_ISO_8601', 4 );
1954 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1956 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1957 * DateTime tag and page 36 for the DateTimeOriginal and
1958 * DateTimeDigitized tags.
1960 define( 'TS_EXIF', 5 );
1963 * Oracle format time.
1965 define( 'TS_ORACLE', 6 );
1968 * Postgres format time.
1970 define( 'TS_POSTGRES', 7 );
1975 define( 'TS_DB2', 8 );
1978 * ISO 8601 basic format with no timezone: 19860209T200000Z
1980 * This is used by ResourceLoader
1982 define( 'TS_ISO_8601_BASIC', 9 );
1985 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1986 * function will autodetect which format is supplied and act
1988 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1989 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1991 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
1999 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2001 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2003 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2005 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2008 $strtime = "@$ts"; // Undocumented?
2009 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2010 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2011 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2012 str_replace( '+00:00', 'UTC', $ts ) );
2013 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2015 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2017 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2019 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2021 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2023 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2024 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2025 '[ \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
2026 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2027 # The regex is a superset of rfc2822 for readability
2028 $strtime = strtok( $ts, ';' );
2029 } 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 ) ) {
2032 } 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 ) ) {
2036 # Bogus value; fall back to the epoch...
2037 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2044 static $formats = array(
2047 TS_DB
=> 'Y-m-d H:i:s',
2048 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
2049 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
2050 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2051 TS_RFC2822
=> 'D, d M Y H:i:s',
2052 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2053 TS_POSTGRES
=> 'Y-m-d H:i:s',
2054 TS_DB2
=> 'Y-m-d H:i:s',
2057 if ( !isset( $formats[$outputtype] ) ) {
2058 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2061 if ( function_exists( "date_create" ) ) {
2062 if ( count( $da ) ) {
2063 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2064 (int)$da[1], (int)$da[2], (int)$da[3],
2065 (int)$da[4], (int)$da[5], (int)$da[6]);
2067 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2068 } elseif ( $strtime ) {
2069 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2075 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2079 $output = $d->format( $formats[$outputtype] );
2081 if ( count( $da ) ) {
2082 // Warning! gmmktime() acts oddly if the month or day is set to 0
2083 // We may want to handle that explicitly at some point
2084 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2085 (int)$da[2], (int)$da[3], (int)$da[1] );
2086 } elseif ( $strtime ) {
2087 $uts = strtotime( $strtime );
2090 if ( $uts === false ) {
2091 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2095 if ( TS_UNIX
== $outputtype ) {
2098 $output = gmdate( $formats[$outputtype], $uts );
2101 if ( ( $outputtype == TS_RFC2822
) ||
( $outputtype == TS_POSTGRES
) ) {
2109 * Return a formatted timestamp, or null if input is null.
2110 * For dealing with nullable timestamp columns in the database.
2111 * @param $outputtype Integer
2115 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2116 if( is_null( $ts ) ) {
2119 return wfTimestamp( $outputtype, $ts );
2124 * Check if the operating system is Windows
2126 * @return Bool: true if it's Windows, False otherwise.
2128 function wfIsWindows() {
2129 static $isWindows = null;
2130 if ( $isWindows === null ) {
2131 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2137 * Swap two variables
2139 function swap( &$x, &$y ) {
2145 function wfGetCachedNotice( $name ) {
2146 global $wgOut, $wgRenderHashAppend, $parserMemc;
2147 $fname = 'wfGetCachedNotice';
2148 wfProfileIn( $fname );
2152 if( $name === 'default' ) {
2154 global $wgSiteNotice;
2155 $notice = $wgSiteNotice;
2156 if( empty( $notice ) ) {
2157 wfProfileOut( $fname );
2161 $notice = wfMsgForContentNoTrans( $name );
2162 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
2163 wfProfileOut( $fname );
2168 // Use the extra hash appender to let eg SSL variants separately cache.
2169 $key = wfMemcKey( $name . $wgRenderHashAppend );
2170 $cachedNotice = $parserMemc->get( $key );
2171 if( is_array( $cachedNotice ) ) {
2172 if( md5( $notice ) == $cachedNotice['hash'] ) {
2173 $notice = $cachedNotice['html'];
2182 if( is_object( $wgOut ) ) {
2183 $parsed = $wgOut->parse( $notice );
2184 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2187 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2191 $notice = '<div id="localNotice">' .$notice . '</div>';
2192 wfProfileOut( $fname );
2196 function wfGetNamespaceNotice() {
2200 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) ) {
2204 $fname = 'wfGetNamespaceNotice';
2205 wfProfileIn( $fname );
2207 $key = 'namespacenotice-' . $wgTitle->getNsText();
2208 $namespaceNotice = wfGetCachedNotice( $key );
2209 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
2210 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2212 $namespaceNotice = '';
2215 wfProfileOut( $fname );
2216 return $namespaceNotice;
2219 function wfGetSiteNotice() {
2221 $fname = 'wfGetSiteNotice';
2222 wfProfileIn( $fname );
2225 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2226 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2227 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2229 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2230 if( !$anonNotice ) {
2231 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2233 $siteNotice = $anonNotice;
2236 if( !$siteNotice ) {
2237 $siteNotice = wfGetCachedNotice( 'default' );
2241 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2242 wfProfileOut( $fname );
2247 * BC wrapper for MimeMagic::singleton()
2248 * @deprecated No longer needed as of 1.17 (r68836).
2250 function &wfGetMimeMagic() {
2251 wfDeprecated( __FUNCTION__
);
2252 return MimeMagic
::singleton();
2256 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2257 * TEMP environment variables are then checked in sequence, and if none are set
2258 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2259 * or C:\Windows\Temp for Windows and hope for the best.
2260 * It is common to call it with tempnam().
2262 * NOTE: When possible, use instead the tmpfile() function to create
2263 * temporary files to avoid race conditions on file creation, etc.
2267 function wfTempDir() {
2268 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2269 $tmp = getenv( $var );
2270 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2274 if( function_exists( 'sys_get_temp_dir' ) ) {
2275 return sys_get_temp_dir();
2278 return wfIsWindows() ?
'C:\Windows\Temp' : '/tmp';
2282 * Make directory, and make all parent directories if they don't exist
2284 * @param $dir String: full path to directory to create
2285 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2286 * @param $caller String: optional caller param for debugging.
2289 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2290 global $wgDirectoryMode;
2292 if ( !is_null( $caller ) ) {
2293 wfDebug( "$caller: called wfMkdirParents($dir)" );
2296 if( strval( $dir ) === '' ||
file_exists( $dir ) ) {
2300 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2302 if ( is_null( $mode ) ) {
2303 $mode = $wgDirectoryMode;
2306 // Turn off the normal warning, we're doing our own below
2307 wfSuppressWarnings();
2308 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2309 wfRestoreWarnings();
2312 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2313 trigger_error( __FUNCTION__
. ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING
);
2319 * Increment a statistics counter
2321 function wfIncrStats( $key ) {
2322 global $wgStatsMethod;
2324 if( $wgStatsMethod == 'udp' ) {
2325 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2328 $socket = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2329 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2333 strlen( $statline ),
2339 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2340 wfSuppressWarnings();
2344 strlen( $statline ),
2349 wfRestoreWarnings();
2350 } elseif( $wgStatsMethod == 'cache' ) {
2352 $key = wfMemcKey( 'stats', $key );
2353 if ( is_null( $wgMemc->incr( $key ) ) ) {
2354 $wgMemc->add( $key, 1 );
2362 * @param $nr Mixed: the number to format
2363 * @param $acc Integer: the number of digits after the decimal point, default 2
2364 * @param $round Boolean: whether or not to round the value, default true
2367 function wfPercent( $nr, $acc = 2, $round = true ) {
2368 $ret = sprintf( "%.${acc}f", $nr );
2369 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2373 * Encrypt a username/password.
2375 * @param $userid Integer: ID of the user
2376 * @param $password String: password of the user
2377 * @return String: hashed password
2378 * @deprecated Use User::crypt() or User::oldCrypt() instead
2380 function wfEncryptPassword( $userid, $password ) {
2381 wfDeprecated(__FUNCTION__
);
2382 # Just wrap around User::oldCrypt()
2383 return User
::oldCrypt( $password, $userid );
2387 * Appends to second array if $value differs from that in $default
2389 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2390 if ( is_null( $changed ) ) {
2391 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2393 if ( $default[$key] !== $value ) {
2394 $changed[$key] = $value;
2399 * Since wfMsg() and co suck, they don't return false if the message key they
2400 * looked up didn't exist but a XHTML string, this function checks for the
2401 * nonexistance of messages by looking at wfMsg() output
2403 * @param $key String: the message key looked up
2404 * @return Boolean True if the message *doesn't* exist.
2406 function wfEmptyMsg( $key ) {
2407 global $wgMessageCache;
2408 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2412 * Find out whether or not a mixed variable exists in a string
2414 * @param $needle String
2415 * @param $str String
2418 function in_string( $needle, $str ) {
2419 return strpos( $str, $needle ) !== false;
2422 function wfSpecialList( $page, $details ) {
2424 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : '';
2425 return $page . $details;
2429 * Returns a regular expression of url protocols
2433 function wfUrlProtocols() {
2434 global $wgUrlProtocols;
2436 static $retval = null;
2437 if ( !is_null( $retval ) ) {
2441 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2442 // with LocalSettings files from 1.5
2443 if ( is_array( $wgUrlProtocols ) ) {
2444 $protocols = array();
2445 foreach ( $wgUrlProtocols as $protocol ) {
2446 $protocols[] = preg_quote( $protocol, '/' );
2449 $retval = implode( '|', $protocols );
2451 $retval = $wgUrlProtocols;
2457 * Safety wrapper around ini_get() for boolean settings.
2458 * The values returned from ini_get() are pre-normalized for settings
2459 * set via php.ini or php_flag/php_admin_flag... but *not*
2460 * for those set via php_value/php_admin_value.
2462 * It's fairly common for people to use php_value instead of php_flag,
2463 * which can leave you with an 'off' setting giving a false positive
2464 * for code that just takes the ini_get() return value as a boolean.
2466 * To make things extra interesting, setting via php_value accepts
2467 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2468 * Unrecognized values go false... again opposite PHP's own coercion
2469 * from string to bool.
2471 * Luckily, 'properly' set settings will always come back as '0' or '1',
2472 * so we only have to worry about them and the 'improper' settings.
2474 * I frickin' hate PHP... :P
2476 * @param $setting String
2479 function wfIniGetBool( $setting ) {
2480 $val = ini_get( $setting );
2481 // 'on' and 'true' can't have whitespace around them, but '1' can.
2482 return strtolower( $val ) == 'on'
2483 ||
strtolower( $val ) == 'true'
2484 ||
strtolower( $val ) == 'yes'
2485 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2489 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2490 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2492 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2494 * @return Bool - Whether or not the extension is loaded
2496 function wfDl( $extension ) {
2497 if( extension_loaded( $extension ) ) {
2501 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2502 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2505 wfSuppressWarnings();
2506 dl( $extension . '.' . PHP_SHLIB_SUFFIX
);
2507 wfRestoreWarnings();
2509 return extension_loaded( $extension );
2513 * Execute a shell command, with time and memory limits mirrored from the PHP
2514 * configuration if supported.
2515 * @param $cmd String Command line, properly escaped for shell.
2516 * @param &$retval optional, will receive the program's exit code.
2517 * (non-zero is usually failure)
2518 * @param $environ Array optional environment variables which should be
2519 * added to the executed command environment.
2520 * @return collected stdout as a string (trailing newlines stripped)
2522 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2523 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2526 if ( is_null( $disabled ) ) {
2528 if( wfIniGetBool( 'safe_mode' ) ) {
2529 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2530 $disabled = 'safemode';
2532 $functions = explode( ',', ini_get( 'disable_functions' ) );
2533 $functions = array_map( 'trim', $functions );
2534 $functions = array_map( 'strtolower', $functions );
2535 if ( in_array( 'passthru', $functions ) ) {
2536 wfDebug( "passthru is in disabled_functions\n" );
2537 $disabled = 'passthru';
2543 return $disabled == 'safemode' ?
2544 'Unable to run external programs in safe mode.' :
2545 'Unable to run external programs, passthru() is disabled.';
2548 wfInitShellLocale();
2551 foreach( $environ as $k => $v ) {
2552 if ( wfIsWindows() ) {
2553 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2554 * appear in the environment variable, so we must use carat escaping as documented in
2555 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2556 * Note however that the quote isn't listed there, but is needed, and the parentheses
2557 * are listed there but doesn't appear to need it.
2559 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . ' && ';
2561 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2562 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2564 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2567 $cmd = $envcmd . $cmd;
2569 if ( wfIsWindows() ) {
2570 if ( version_compare( PHP_VERSION
, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2571 ( version_compare( PHP_VERSION
, '5.2.1', '>=' ) ||
php_uname( 's' ) == 'Windows NT' ) )
2573 # Hack to work around PHP's flawed invocation of cmd.exe
2574 # http://news.php.net/php.internals/21796
2575 # Windows 9x doesn't accept any kind of quotes
2576 $cmd = '"' . $cmd . '"';
2578 } elseif ( php_uname( 's' ) == 'Linux' ) {
2579 $time = intval( $wgMaxShellTime );
2580 $mem = intval( $wgMaxShellMemory );
2581 $filesize = intval( $wgMaxShellFileSize );
2583 if ( $time > 0 && $mem > 0 ) {
2584 $script = "$IP/bin/ulimit4.sh";
2585 if ( is_executable( $script ) ) {
2586 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2590 wfDebug( "wfShellExec: $cmd\n" );
2592 $retval = 1; // error by default?
2594 passthru( $cmd, $retval );
2595 $output = ob_get_contents();
2598 if ( $retval == 127 ) {
2599 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2605 * Workaround for http://bugs.php.net/bug.php?id=45132
2606 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2608 function wfInitShellLocale() {
2609 static $done = false;
2614 global $wgShellLocale;
2615 if ( !wfIniGetBool( 'safe_mode' ) ) {
2616 putenv( "LC_CTYPE=$wgShellLocale" );
2617 setlocale( LC_CTYPE
, $wgShellLocale );
2622 * This function works like "use VERSION" in Perl, the program will die with a
2623 * backtrace if the current version of PHP is less than the version provided
2625 * This is useful for extensions which due to their nature are not kept in sync
2626 * with releases, and might depend on other versions of PHP than the main code
2628 * Note: PHP might die due to parsing errors in some cases before it ever
2629 * manages to call this function, such is life
2631 * @see perldoc -f use
2633 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2636 function wfUsePHP( $req_ver ) {
2637 $php_ver = PHP_VERSION
;
2639 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2640 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2645 * This function works like "use VERSION" in Perl except it checks the version
2646 * of MediaWiki, the program will die with a backtrace if the current version
2647 * of MediaWiki is less than the version provided.
2649 * This is useful for extensions which due to their nature are not kept in sync
2652 * @see perldoc -f use
2654 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2657 function wfUseMW( $req_ver ) {
2660 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2661 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2666 * Return the final portion of a pathname.
2667 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2668 * http://bugs.php.net/bug.php?id=33898
2670 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2671 * We'll consider it so always, as we don't want \s in our Unix paths either.
2673 * @param $path String
2674 * @param $suffix String: to remove if present
2677 function wfBaseName( $path, $suffix = '' ) {
2678 $encSuffix = ( $suffix == '' )
2680 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2682 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2690 * Generate a relative path name to the given file.
2691 * May explode on non-matching case-insensitive paths,
2692 * funky symlinks, etc.
2694 * @param $path String: absolute destination path including target filename
2695 * @param $from String: Absolute source path, directory only
2698 function wfRelativePath( $path, $from ) {
2699 // Normalize mixed input on Windows...
2700 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2701 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2703 // Trim trailing slashes -- fix for drive root
2704 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2705 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2707 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2708 $against = explode( DIRECTORY_SEPARATOR
, $from );
2710 if( $pieces[0] !== $against[0] ) {
2711 // Non-matching Windows drive letters?
2712 // Return a full path.
2716 // Trim off common prefix
2717 while( count( $pieces ) && count( $against )
2718 && $pieces[0] == $against[0] ) {
2719 array_shift( $pieces );
2720 array_shift( $against );
2723 // relative dots to bump us to the parent
2724 while( count( $against ) ) {
2725 array_unshift( $pieces, '..' );
2726 array_shift( $against );
2729 array_push( $pieces, wfBaseName( $path ) );
2731 return implode( DIRECTORY_SEPARATOR
, $pieces );
2735 * Backwards array plus for people who haven't bothered to read the PHP manual
2736 * XXX: will not darn your socks for you.
2738 * @param $array1 Array
2739 * @param [$array2, [...]] Arrays
2742 function wfArrayMerge( $array1/* ... */ ) {
2743 $args = func_get_args();
2744 $args = array_reverse( $args, true );
2746 foreach ( $args as $arg ) {
2753 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2755 * wfMergeErrorArrays(
2756 * array( array( 'x' ) ),
2757 * array( array( 'x', '2' ) ),
2758 * array( array( 'x' ) ),
2759 * array( array( 'y') )
2763 * array( 'x', '2' ),
2768 function wfMergeErrorArrays( /*...*/ ) {
2769 $args = func_get_args();
2771 foreach ( $args as $errors ) {
2772 foreach ( $errors as $params ) {
2773 # FIXME: sometimes get nested arrays for $params,
2774 # which leads to E_NOTICEs
2775 $spec = implode( "\t", $params );
2776 $out[$spec] = $params;
2779 return array_values( $out );
2783 * parse_url() work-alike, but non-broken. Differences:
2785 * 1) Does not raise warnings on bad URLs (just returns false)
2786 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2787 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2789 * @param $url String: a URL to parse
2790 * @return Array: bits of the URL in an associative array, per PHP docs
2792 function wfParseUrl( $url ) {
2793 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2794 wfSuppressWarnings();
2795 $bits = parse_url( $url );
2796 wfRestoreWarnings();
2801 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2802 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2803 $bits['delimiter'] = '://';
2804 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2805 $bits['delimiter'] = ':';
2806 // parse_url detects for news: and mailto: the host part of an url as path
2807 // We have to correct this wrong detection
2808 if ( isset( $bits['path'] ) ) {
2809 $bits['host'] = $bits['path'];
2820 * Make a URL index, appropriate for the el_index field of externallinks.
2822 function wfMakeUrlIndex( $url ) {
2823 $bits = wfParseUrl( $url );
2825 // Reverse the labels in the hostname, convert to lower case
2826 // For emails reverse domainpart only
2827 if ( $bits['scheme'] == 'mailto' ) {
2828 $mailparts = explode( '@', $bits['host'], 2 );
2829 if ( count( $mailparts ) === 2 ) {
2830 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2832 // No domain specified, don't mangle it
2835 $reversedHost = $domainpart . '@' . $mailparts[0];
2837 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2839 // Add an extra dot to the end
2840 // Why? Is it in wrong place in mailto links?
2841 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2842 $reversedHost .= '.';
2844 // Reconstruct the pseudo-URL
2845 $prot = $bits['scheme'];
2846 $index = $prot . $bits['delimiter'] . $reversedHost;
2847 // Leave out user and password. Add the port, path, query and fragment
2848 if ( isset( $bits['port'] ) ) {
2849 $index .= ':' . $bits['port'];
2851 if ( isset( $bits['path'] ) ) {
2852 $index .= $bits['path'];
2856 if ( isset( $bits['query'] ) ) {
2857 $index .= '?' . $bits['query'];
2859 if ( isset( $bits['fragment'] ) ) {
2860 $index .= '#' . $bits['fragment'];
2866 * Do any deferred updates and clear the list
2867 * TODO: This could be in Wiki.php if that class made any sense at all
2869 function wfDoUpdates() {
2870 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2871 foreach ( $wgDeferredUpdateList as $update ) {
2872 $update->doUpdate();
2874 foreach ( $wgPostCommitUpdateList as $update ) {
2875 $update->doUpdate();
2877 $wgDeferredUpdateList = array();
2878 $wgPostCommitUpdateList = array();
2882 * Convert an arbitrarily-long digit string from one numeric base
2883 * to another, optionally zero-padding to a minimum column width.
2885 * Supports base 2 through 36; digit values 10-36 are represented
2886 * as lowercase letters a-z. Input is case-insensitive.
2888 * @param $input String: of digits
2889 * @param $sourceBase Integer: 2-36
2890 * @param $destBase Integer: 2-36
2891 * @param $pad Integer: 1 or greater
2892 * @param $lowercase Boolean
2893 * @return String or false on invalid input
2895 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2896 $input = strval( $input );
2897 if( $sourceBase < 2 ||
2902 $sourceBase != intval( $sourceBase ) ||
2903 $destBase != intval( $destBase ) ||
2904 $pad != intval( $pad ) ||
2905 !is_string( $input ) ||
2909 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2910 $inDigits = array();
2913 // Decode and validate input string
2914 $input = strtolower( $input );
2915 for( $i = 0; $i < strlen( $input ); $i++
) {
2916 $n = strpos( $digitChars, $input{$i} );
2917 if( $n === false ||
$n > $sourceBase ) {
2923 // Iterate over the input, modulo-ing out an output digit
2924 // at a time until input is gone.
2925 while( count( $inDigits ) ) {
2927 $workDigits = array();
2930 foreach( $inDigits as $digit ) {
2931 $work *= $sourceBase;
2934 if( $work < $destBase ) {
2935 // Gonna need to pull another digit.
2936 if( count( $workDigits ) ) {
2937 // Avoid zero-padding; this lets us find
2938 // the end of the input very easily when
2939 // length drops to zero.
2943 // Finally! Actual division!
2944 $workDigits[] = intval( $work / $destBase );
2946 // Isn't it annoying that most programming languages
2947 // don't have a single divide-and-remainder operator,
2948 // even though the CPU implements it that way?
2949 $work = $work %
$destBase;
2953 // All that division leaves us with a remainder,
2954 // which is conveniently our next output digit.
2955 $outChars .= $digitChars[$work];
2958 $inDigits = $workDigits;
2961 while( strlen( $outChars ) < $pad ) {
2965 return strrev( $outChars );
2969 * Create an object with a given name and an array of construct parameters
2970 * @param $name String
2971 * @param $p Array: parameters
2973 function wfCreateObject( $name, $p ) {
2974 $p = array_values( $p );
2975 switch ( count( $p ) ) {
2979 return new $name( $p[0] );
2981 return new $name( $p[0], $p[1] );
2983 return new $name( $p[0], $p[1], $p[2] );
2985 return new $name( $p[0], $p[1], $p[2], $p[3] );
2987 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2989 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2991 throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
2995 function wfHttpOnlySafe() {
2996 global $wgHttpOnlyBlacklist;
2997 if( !version_compare( '5.2', PHP_VERSION
, '<' ) ) {
3001 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3002 foreach( $wgHttpOnlyBlacklist as $regex ) {
3003 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3013 * Initialise php session
3015 function wfSetupSession( $sessionId = false ) {
3016 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3017 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3018 if( $wgSessionsInMemcached ) {
3019 require_once( 'MemcachedSessions.php' );
3020 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3021 # Only set this if $wgSessionHandler isn't null and session.save_handler
3022 # hasn't already been set to the desired value (that causes errors)
3023 ini_set( 'session.save_handler', $wgSessionHandler );
3025 $httpOnlySafe = wfHttpOnlySafe();
3026 wfDebugLog( 'cookie',
3027 'session_set_cookie_params: "' . implode( '", "',
3033 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
3034 if( $httpOnlySafe && $wgCookieHttpOnly ) {
3035 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3037 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
3038 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
3040 session_cache_limiter( 'private, must-revalidate' );
3042 session_id( $sessionId );
3044 wfSuppressWarnings();
3046 wfRestoreWarnings();
3050 * Get an object from the precompiled serialized directory
3052 * @return Mixed: the variable on success, false on failure
3054 function wfGetPrecompiledData( $name ) {
3057 $file = "$IP/serialized/$name";
3058 if ( file_exists( $file ) ) {
3059 $blob = file_get_contents( $file );
3061 return unserialize( $blob );
3067 function wfGetCaller( $level = 2 ) {
3068 $backtrace = wfDebugBacktrace();
3069 if ( isset( $backtrace[$level] ) ) {
3070 return wfFormatStackFrame( $backtrace[$level] );
3072 $caller = 'unknown';
3078 * Return a string consisting of callers in the stack. Useful sometimes
3079 * for profiling specific points.
3081 * @param $limit The maximum depth of the stack frame to return, or false for
3084 function wfGetAllCallers( $limit = 3 ) {
3085 $trace = array_reverse( wfDebugBacktrace() );
3086 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
3087 $limit = count( $trace ) - 1;
3089 $trace = array_slice( $trace, -$limit - 1, $limit );
3090 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3094 * Return a string representation of frame
3096 function wfFormatStackFrame( $frame ) {
3097 return isset( $frame['class'] ) ?
3098 $frame['class'] . '::' . $frame['function'] :
3105 function wfMemcKey( /*... */ ) {
3106 $args = func_get_args();
3107 $key = wfWikiID() . ':' . implode( ':', $args );
3108 $key = str_replace( ' ', '_', $key );
3113 * Get a cache key for a foreign DB
3115 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3116 $args = array_slice( func_get_args(), 2 );
3118 $key = "$db-$prefix:" . implode( ':', $args );
3120 $key = $db . ':' . implode( ':', $args );
3126 * Get an ASCII string identifying this wiki
3127 * This is used as a prefix in memcached keys
3129 function wfWikiID() {
3130 global $wgDBprefix, $wgDBname;
3131 if ( $wgDBprefix ) {
3132 return "$wgDBname-$wgDBprefix";
3139 * Split a wiki ID into DB name and table prefix
3141 function wfSplitWikiID( $wiki ) {
3142 $bits = explode( '-', $wiki, 2 );
3143 if ( count( $bits ) < 2 ) {
3150 * Get a Database object.
3151 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3152 * master (for write queries), DB_SLAVE for potentially lagged read
3153 * queries, or an integer >= 0 for a particular server.
3155 * @param $groups Mixed: query groups. An array of group names that this query
3156 * belongs to. May contain a single string if the query is only
3159 * @param $wiki String: the wiki ID, or false for the current wiki
3161 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3162 * will always return the same object, unless the underlying connection or load
3163 * balancer is manually destroyed.
3165 * @return DatabaseBase
3167 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3168 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3172 * Get a load balancer object.
3174 * @param $wiki String: wiki ID, or false for the current wiki
3175 * @return LoadBalancer
3177 function wfGetLB( $wiki = false ) {
3178 return wfGetLBFactory()->getMainLB( $wiki );
3182 * Get the load balancer factory object
3184 function &wfGetLBFactory() {
3185 return LBFactory
::singleton();
3190 * Shortcut for RepoGroup::singleton()->findFile()
3191 * @param $title String or Title object
3192 * @param $options Associative array of options:
3193 * time: requested time for an archived image, or false for the
3194 * current version. An image object will be returned which was
3195 * created at the specified time.
3197 * ignoreRedirect: If true, do not follow file redirects
3199 * private: If true, return restricted (deleted) files if the current
3200 * user is allowed to view them. Otherwise, such files will not
3203 * bypassCache: If true, do not use the process-local cache of File objects
3205 * @return File, or false if the file does not exist
3207 function wfFindFile( $title, $options = array() ) {
3208 return RepoGroup
::singleton()->findFile( $title, $options );
3212 * Get an object referring to a locally registered file.
3213 * Returns a valid placeholder object if the file does not exist.
3214 * @param $title Title or String
3215 * @return File, or null if passed an invalid Title
3217 function wfLocalFile( $title ) {
3218 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3222 * Should low-performance queries be disabled?
3226 function wfQueriesMustScale() {
3227 global $wgMiserMode;
3229 ||
( SiteStats
::pages() > 100000
3230 && SiteStats
::edits() > 1000000
3231 && SiteStats
::users() > 10000 );
3235 * Get the path to a specified script file, respecting file
3236 * extensions; this is a wrapper around $wgScriptExtension etc.
3238 * @param $script String: script filename, sans extension
3241 function wfScript( $script = 'index' ) {
3242 global $wgScriptPath, $wgScriptExtension;
3243 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3247 * Get the script URL.
3249 * @return script URL
3251 function wfGetScriptUrl() {
3252 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3254 # as it was called, minus the query string.
3256 # Some sites use Apache rewrite rules to handle subdomains,
3257 # and have PHP set up in a weird way that causes PHP_SELF
3258 # to contain the rewritten URL instead of the one that the
3259 # outside world sees.
3261 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3262 # provides containing the "before" URL.
3263 return $_SERVER['SCRIPT_NAME'];
3265 return $_SERVER['URL'];
3270 * Convenience function converts boolean values into "true"
3271 * or "false" (string) values
3273 * @param $value Boolean
3276 function wfBoolToStr( $value ) {
3277 return $value ?
'true' : 'false';
3281 * Load an extension messages file
3282 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3284 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3288 * Get a platform-independent path to the null file, e.g.
3293 function wfGetNull() {
3294 return wfIsWindows()
3300 * Displays a maxlag error
3302 * @param $host String: server that lags the most
3303 * @param $lag Integer: maxlag (actual)
3304 * @param $maxLag Integer: maxlag (requested)
3306 function wfMaxlagError( $host, $lag, $maxLag ) {
3307 global $wgShowHostnames;
3308 header( 'HTTP/1.1 503 Service Unavailable' );
3309 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3310 header( 'X-Database-Lag: ' . intval( $lag ) );
3311 header( 'Content-Type: text/plain' );
3312 if( $wgShowHostnames ) {
3313 echo "Waiting for $host: $lag seconds lagged\n";
3315 echo "Waiting for a database server: $lag seconds lagged\n";
3320 * Throws a warning that $function is deprecated
3321 * @param $function String
3324 function wfDeprecated( $function ) {
3325 static $functionsWarned = array();
3326 if ( !isset( $functionsWarned[$function] ) ) {
3327 $functionsWarned[$function] = true;
3328 wfWarn( "Use of $function is deprecated.", 2 );
3333 * Send a warning either to the debug log or in a PHP error depending on
3334 * $wgDevelopmentWarnings
3336 * @param $msg String: message to send
3337 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3338 * find the correct caller (1 = function calling wfWarn, ...)
3339 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3342 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
3343 $callers = wfDebugBacktrace();
3344 if( isset( $callers[$callerOffset +
1] ) ){
3345 $callerfunc = $callers[$callerOffset +
1];
3346 $callerfile = $callers[$callerOffset];
3347 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3348 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3350 $file = '(internal function)';
3353 if( isset( $callerfunc['class'] ) ) {
3354 $func .= $callerfunc['class'] . '::';
3356 if( isset( $callerfunc['function'] ) ) {
3357 $func .= $callerfunc['function'];
3359 $msg .= " [Called from $func in $file]";
3362 global $wgDevelopmentWarnings;
3363 if ( $wgDevelopmentWarnings ) {
3364 trigger_error( $msg, $level );
3366 wfDebug( "$msg\n" );
3371 * Sleep until the worst slave's replication lag is less than or equal to
3372 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3373 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3374 * a no-op if there are no slaves.
3376 * Every time the function has to wait for a slave, it will print a message to
3377 * that effect (and then sleep for a little while), so it's probably not best
3378 * to use this outside maintenance scripts in its present form.
3380 * @param $maxLag Integer
3381 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3384 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3386 $lb = wfGetLB( $wiki );
3387 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3388 while( $lag > $maxLag ) {
3389 wfSuppressWarnings();
3390 $name = gethostbyaddr( $host );
3391 wfRestoreWarnings();
3392 if( $name !== false ) {
3395 print "Waiting for $host (lagged $lag seconds)...\n";
3397 list( $host, $lag ) = $lb->getMaxLag();
3403 * Output some plain text in command-line mode or in the installer (updaters.inc).
3404 * Do not use it in any other context, its behaviour is subject to change.
3406 function wfOut( $s ) {
3407 global $wgCommandLineMode;
3408 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3411 echo htmlspecialchars( $s );
3417 * Count down from $n to zero on the terminal, with a one-second pause
3418 * between showing each number. For use in command-line scripts.
3420 function wfCountDown( $n ) {
3421 for ( $i = $n; $i >= 0; $i-- ) {
3423 echo str_repeat( "\x08", strlen( $i +
1 ) );
3435 * Generate a random 32-character hexadecimal token.
3436 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3437 * characters before hashing.
3439 function wfGenerateToken( $salt = '' ) {
3440 $salt = serialize( $salt );
3441 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3445 * Replace all invalid characters with -
3446 * @param $name Mixed: filename to process
3448 function wfStripIllegalFilenameChars( $name ) {
3449 global $wgIllegalFileChars;
3450 $name = wfBaseName( $name );
3451 $name = preg_replace(
3452 "/[^" . Title
::legalChars() . "]" .
3453 ( $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '' ) .
3462 * Insert array into another array after the specified *KEY*
3463 * @param $array Array: The array.
3464 * @param $insert Array: The array to insert.
3465 * @param $after Mixed: The key to insert after
3467 function wfArrayInsertAfter( $array, $insert, $after ) {
3468 // Find the offset of the element to insert after.
3469 $keys = array_keys( $array );
3470 $offsetByKey = array_flip( $keys );
3472 $offset = $offsetByKey[$after];
3474 // Insert at the specified offset
3475 $before = array_slice( $array, 0, $offset +
1, true );
3476 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
3478 $output = $before +
$insert +
$after;
3483 /* Recursively converts the parameter (an object) to an array with the same data */
3484 function wfObjectToArray( $object, $recursive = true ) {
3486 foreach ( get_object_vars( $object ) as $key => $value ) {
3487 if ( is_object( $value ) && $recursive ) {
3488 $value = wfObjectToArray( $value );
3491 $array[$key] = $value;
3498 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3499 * @return Integer value memory was set to.
3501 function wfMemoryLimit() {
3502 global $wgMemoryLimit;
3503 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3504 if( $memlimit != -1 ) {
3505 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3506 if( $conflimit == -1 ) {
3507 wfDebug( "Removing PHP's memory limit\n" );
3508 wfSuppressWarnings();
3509 ini_set( 'memory_limit', $conflimit );
3510 wfRestoreWarnings();
3512 } elseif ( $conflimit > $memlimit ) {
3513 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3514 wfSuppressWarnings();
3515 ini_set( 'memory_limit', $conflimit );
3516 wfRestoreWarnings();
3524 * Converts shorthand byte notation to integer form
3525 * @param $string String
3528 function wfShorthandToInteger( $string = '' ) {
3529 $string = trim( $string );
3530 if( $string === '' ) {
3533 $last = $string[strlen( $string ) - 1];
3534 $val = intval( $string );
3539 // break intentionally missing
3543 // break intentionally missing
3553 * Get the normalised IETF language tag
3554 * @param $code String: The language code.
3555 * @return $langCode String: The language code which complying with BCP 47 standards.
3557 function wfBCP47( $code ) {
3558 $codeSegment = explode( '-', $code );
3559 foreach ( $codeSegment as $segNo => $seg ) {
3560 if ( count( $codeSegment ) > 0 ) {
3561 // ISO 3166 country code
3562 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3563 $codeBCP[$segNo] = strtoupper( $seg );
3564 // ISO 15924 script code
3565 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3566 $codeBCP[$segNo] = ucfirst( $seg );
3567 // Use lowercase for other cases
3569 $codeBCP[$segNo] = strtolower( $seg );
3572 // Use lowercase for single segment
3573 $codeBCP[$segNo] = strtolower( $seg );
3576 $langCode = implode( '-', $codeBCP );
3580 function wfArrayMap( $function, $input ) {
3581 $ret = array_map( $function, $input );
3582 foreach ( $ret as $key => $value ) {
3583 $taint = istainted( $input[$key] );
3585 taint( $ret[$key], $taint );