/includes/GlobalFunctions.php
PHP | 3619 lines | 2297 code | 285 blank | 1037 comment | 395 complexity | 5380fae10701aef4cdee98dc40ab1add MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Global functions used everywhere
- * @file
- */
-
- if ( !defined( 'MEDIAWIKI' ) ) {
- die( "This file is part of MediaWiki, it is not a valid entry point" );
- }
-
- require_once dirname( __FILE__ ) . '/normal/UtfNormalUtil.php';
-
- // Hide compatibility functions from Doxygen
- /// @cond
-
- /**
- * Compatibility functions
- *
- * We support PHP 5.1.x and up.
- * Re-implementations of newer functions or functions in non-standard
- * PHP extensions may be included here.
- */
- if( !function_exists( 'iconv' ) ) {
- # iconv support is not in the default configuration and so may not be present.
- # Assume will only ever use utf-8 and iso-8859-1.
- # This will *not* work in all circumstances.
- function iconv( $from, $to, $string ) {
- if ( substr( $to, -8 ) == '//IGNORE' ) {
- $to = substr( $to, 0, strlen( $to ) - 8 );
- }
- if( strcasecmp( $from, $to ) == 0 ) {
- return $string;
- }
- if( strcasecmp( $from, 'utf-8' ) == 0 ) {
- return utf8_decode( $string );
- }
- if( strcasecmp( $to, 'utf-8' ) == 0 ) {
- return utf8_encode( $string );
- }
- return $string;
- }
- }
-
- if ( !function_exists( 'mb_substr' ) ) {
- /**
- * Fallback implementation for mb_substr, hardcoded to UTF-8.
- * Attempts to be at least _moderately_ efficient; best optimized
- * for relatively small offset and count values -- about 5x slower
- * than native mb_string in my testing.
- *
- * Larger offsets are still fairly efficient for Latin text, but
- * can be up to 100x slower than native if the text is heavily
- * multibyte and we have to slog through a few hundred kb.
- */
- function mb_substr( $str, $start, $count='end' ) {
- if( $start != 0 ) {
- $split = mb_substr_split_unicode( $str, intval( $start ) );
- $str = substr( $str, $split );
- }
-
- if( $count !== 'end' ) {
- $split = mb_substr_split_unicode( $str, intval( $count ) );
- $str = substr( $str, 0, $split );
- }
-
- return $str;
- }
-
- function mb_substr_split_unicode( $str, $splitPos ) {
- if( $splitPos == 0 ) {
- return 0;
- }
-
- $byteLen = strlen( $str );
-
- if( $splitPos > 0 ) {
- if( $splitPos > 256 ) {
- // Optimize large string offsets by skipping ahead N bytes.
- // This will cut out most of our slow time on Latin-based text,
- // and 1/2 to 1/3 on East European and Asian scripts.
- $bytePos = $splitPos;
- while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
- ++$bytePos;
- }
- $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
- } else {
- $charPos = 0;
- $bytePos = 0;
- }
-
- while( $charPos++ < $splitPos ) {
- ++$bytePos;
- // Move past any tail bytes
- while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
- ++$bytePos;
- }
- }
- } else {
- $splitPosX = $splitPos + 1;
- $charPos = 0; // relative to end of string; we don't care about the actual char position here
- $bytePos = $byteLen;
- while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
- --$bytePos;
- // Move past any tail bytes
- while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
- --$bytePos;
- }
- }
- }
-
- return $bytePos;
- }
- }
-
- if ( !function_exists( 'mb_strlen' ) ) {
- /**
- * Fallback implementation of mb_strlen, hardcoded to UTF-8.
- * @param string $str
- * @param string $enc optional encoding; ignored
- * @return int
- */
- function mb_strlen( $str, $enc = '' ) {
- $counts = count_chars( $str );
- $total = 0;
-
- // Count ASCII bytes
- for( $i = 0; $i < 0x80; $i++ ) {
- $total += $counts[$i];
- }
-
- // Count multibyte sequence heads
- for( $i = 0xc0; $i < 0xff; $i++ ) {
- $total += $counts[$i];
- }
- return $total;
- }
- }
-
-
- if( !function_exists( 'mb_strpos' ) ) {
- /**
- * Fallback implementation of mb_strpos, hardcoded to UTF-8.
- * @param $haystack String
- * @param $needle String
- * @param $offset String: optional start position
- * @param $encoding String: optional encoding; ignored
- * @return int
- */
- function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
- $needle = preg_quote( $needle, '/' );
-
- $ar = array();
- preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
-
- if( isset( $ar[0][1] ) ) {
- return $ar[0][1];
- } else {
- return false;
- }
- }
- }
-
- if( !function_exists( 'mb_strrpos' ) ) {
- /**
- * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
- * @param $haystack String
- * @param $needle String
- * @param $offset String: optional start position
- * @param $encoding String: optional encoding; ignored
- * @return int
- */
- function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
- $needle = preg_quote( $needle, '/' );
-
- $ar = array();
- preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
-
- if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
- isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
- return $ar[0][count( $ar[0] ) - 1][1];
- } else {
- return false;
- }
- }
- }
-
- // Support for Wietse Venema's taint feature
- if ( !function_exists( 'istainted' ) ) {
- function istainted( $var ) {
- return 0;
- }
- function taint( $var, $level = 0 ) {}
- function untaint( $var, $level = 0 ) {}
- define( 'TC_HTML', 1 );
- define( 'TC_SHELL', 1 );
- define( 'TC_MYSQL', 1 );
- define( 'TC_PCRE', 1 );
- define( 'TC_SELF', 1 );
- }
-
- // array_fill_keys() was only added in 5.2, but people use it anyway
- // add a back-compat layer for 5.1. See bug 27781
- if( !function_exists( 'array_fill_keys' ) ) {
- function array_fill_keys( $keys, $value ) {
- return array_combine( $keys, array_fill( 0, count( $keys ), $value ) );
- }
- }
-
-
- /// @endcond
-
-
- /**
- * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
- */
- function wfArrayDiff2( $a, $b ) {
- return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
- }
- function wfArrayDiff2_cmp( $a, $b ) {
- if ( !is_array( $a ) ) {
- return strcmp( $a, $b );
- } elseif ( count( $a ) !== count( $b ) ) {
- return count( $a ) < count( $b ) ? -1 : 1;
- } else {
- reset( $a );
- reset( $b );
- while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
- $cmp = strcmp( $valueA, $valueB );
- if ( $cmp !== 0 ) {
- return $cmp;
- }
- }
- return 0;
- }
- }
-
- /**
- * Seed Mersenne Twister
- * No-op for compatibility; only necessary in PHP < 4.2.0
- * @deprecated. Remove in 1.18
- */
- function wfSeedRandom() {
- wfDeprecated(__FUNCTION__);
- }
-
- /**
- * Get a random decimal value between 0 and 1, in a way
- * not likely to give duplicate values for any realistic
- * number of articles.
- *
- * @return string
- */
- function wfRandom() {
- # The maximum random value is "only" 2^31-1, so get two random
- # values to reduce the chance of dupes
- $max = mt_getrandmax() + 1;
- $rand = number_format( ( mt_rand() * $max + mt_rand() )
- / $max / $max, 12, '.', '' );
- return $rand;
- }
-
- /**
- * We want some things to be included as literal characters in our title URLs
- * for prettiness, which urlencode encodes by default. According to RFC 1738,
- * all of the following should be safe:
- *
- * ;:@&=$-_.+!*'(),
- *
- * But + is not safe because it's used to indicate a space; &= are only safe in
- * paths and not in queries (and we don't distinguish here); ' seems kind of
- * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
- * is reserved, we don't care. So the list we unescape is:
- *
- * ;:@$!*(),/
- *
- * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
- * so no fancy : for IIS7.
- *
- * %2F in the page titles seems to fatally break for some reason.
- *
- * @param $s String:
- * @return string
- */
- function wfUrlencode( $s ) {
- static $needle;
- if ( is_null( $needle ) ) {
- $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
- if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
- $needle[] = '%3A';
- }
- }
-
- $s = urlencode( $s );
- $s = str_ireplace(
- $needle,
- array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
- $s
- );
-
- return $s;
- }
-
- /**
- * Sends a line to the debug log if enabled or, optionally, to a comment in output.
- * In normal operation this is a NOP.
- *
- * Controlling globals:
- * $wgDebugLogFile - points to the log file
- * $wgProfileOnly - if set, normal debug messages will not be recorded.
- * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
- * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
- *
- * @param $text String
- * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
- */
- function wfDebug( $text, $logonly = false ) {
- global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
- global $wgDebugLogPrefix, $wgShowDebug;
- static $recursion = 0;
-
- static $cache = array(); // Cache of unoutputted messages
- $text = wfDebugTimer() . $text;
-
- # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
- if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
- return;
- }
-
- if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
- $cache[] = $text;
-
- if ( !isset( $wgOut ) ) {
- return;
- }
- if ( !StubObject::isRealObject( $wgOut ) ) {
- if ( $recursion ) {
- return;
- }
- $recursion++;
- $wgOut->_unstub();
- $recursion--;
- }
-
- // add the message and possible cached ones to the output
- array_map( array( $wgOut, 'debug' ), $cache );
- $cache = array();
- }
- if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
- # Strip unprintables; they can switch terminal modes when binary data
- # gets dumped, which is pretty annoying.
- $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
- $text = $wgDebugLogPrefix . $text;
- wfErrorLog( $text, $wgDebugLogFile );
- }
- }
-
- function wfDebugTimer() {
- global $wgDebugTimestamps;
- if ( !$wgDebugTimestamps ) {
- return '';
- }
- static $start = null;
-
- if ( $start === null ) {
- $start = microtime( true );
- $prefix = "\n$start";
- } else {
- $prefix = sprintf( "%6.4f", microtime( true ) - $start );
- }
-
- return $prefix . ' ';
- }
-
- /**
- * Send a line giving PHP memory usage.
- * @param $exact Bool: print exact values instead of kilobytes (default: false)
- */
- function wfDebugMem( $exact = false ) {
- $mem = memory_get_usage();
- if( !$exact ) {
- $mem = floor( $mem / 1024 ) . ' kilobytes';
- } else {
- $mem .= ' bytes';
- }
- wfDebug( "Memory usage: $mem\n" );
- }
-
- /**
- * Send a line to a supplementary debug log file, if configured, or main debug log if not.
- * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
- *
- * @param $logGroup String
- * @param $text String
- * @param $public Bool: whether to log the event in the public log if no private
- * log file is specified, (default true)
- */
- function wfDebugLog( $logGroup, $text, $public = true ) {
- global $wgDebugLogGroups, $wgShowHostnames;
- $text = trim( $text ) . "\n";
- if( isset( $wgDebugLogGroups[$logGroup] ) ) {
- $time = wfTimestamp( TS_DB );
- $wiki = wfWikiID();
- if ( $wgShowHostnames ) {
- $host = wfHostname();
- } else {
- $host = '';
- }
- wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
- } elseif ( $public === true ) {
- wfDebug( $text, true );
- }
- }
-
- /**
- * Log for database errors
- * @param $text String: database error message.
- */
- function wfLogDBError( $text ) {
- global $wgDBerrorLog, $wgDBname;
- if ( $wgDBerrorLog ) {
- $host = trim(`hostname`);
- $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
- wfErrorLog( $text, $wgDBerrorLog );
- }
- }
-
- /**
- * Log to a file without getting "file size exceeded" signals.
- *
- * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
- * send lines to the specified port, prefixed by the specified prefix and a space.
- */
- function wfErrorLog( $text, $file ) {
- if ( substr( $file, 0, 4 ) == 'udp:' ) {
- # Needs the sockets extension
- if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
- // IPv6 bracketed host
- $host = $m[2];
- $port = intval( $m[3] );
- $prefix = isset( $m[4] ) ? $m[4] : false;
- $domain = AF_INET6;
- } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
- $host = $m[2];
- if ( !IP::isIPv4( $host ) ) {
- $host = gethostbyname( $host );
- }
- $port = intval( $m[3] );
- $prefix = isset( $m[4] ) ? $m[4] : false;
- $domain = AF_INET;
- } else {
- throw new MWException( __METHOD__ . ': Invalid UDP specification' );
- }
- // Clean it up for the multiplexer
- if ( strval( $prefix ) !== '' ) {
- $text = preg_replace( '/^/m', $prefix . ' ', $text );
- if ( substr( $text, -1 ) != "\n" ) {
- $text .= "\n";
- }
- }
-
- $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
- if ( !$sock ) {
- return;
- }
- socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
- socket_close( $sock );
- } else {
- wfSuppressWarnings();
- $exists = file_exists( $file );
- $size = $exists ? filesize( $file ) : false;
- if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
- error_log( $text, 3, $file );
- }
- wfRestoreWarnings();
- }
- }
-
- /**
- * @todo document
- */
- function wfLogProfilingData() {
- global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
- global $wgProfiler, $wgProfileLimit, $wgUser;
- # Profiling must actually be enabled...
- if( is_null( $wgProfiler ) ) {
- return;
- }
- # Get total page request time
- $now = wfTime();
- $elapsed = $now - $wgRequestTime;
- # Only show pages that longer than $wgProfileLimit time (default is 0)
- if( $elapsed <= $wgProfileLimit ) {
- return;
- }
- $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
- $forward = '';
- if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
- $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
- }
- if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
- $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
- }
- if( !empty( $_SERVER['HTTP_FROM'] ) ) {
- $forward .= ' from ' . $_SERVER['HTTP_FROM'];
- }
- if( $forward ) {
- $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
- }
- // Don't unstub $wgUser at this late stage just for statistics purposes
- // FIXME: We can detect some anons even if it is not loaded. See User::getId()
- if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
- $forward .= ' anon';
- }
- $log = sprintf( "%s\t%04.3f\t%s\n",
- gmdate( 'YmdHis' ), $elapsed,
- urldecode( $wgRequest->getRequestURL() . $forward ) );
- if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
- wfErrorLog( $log . $prof, $wgDebugLogFile );
- }
- }
-
- /**
- * Check if the wiki read-only lock file is present. This can be used to lock
- * off editing functions, but doesn't guarantee that the database will not be
- * modified.
- * @return bool
- */
- function wfReadOnly() {
- global $wgReadOnlyFile, $wgReadOnly;
-
- if ( !is_null( $wgReadOnly ) ) {
- return (bool)$wgReadOnly;
- }
- if ( $wgReadOnlyFile == '' ) {
- return false;
- }
- // Set $wgReadOnly for faster access next time
- if ( is_file( $wgReadOnlyFile ) ) {
- $wgReadOnly = file_get_contents( $wgReadOnlyFile );
- } else {
- $wgReadOnly = false;
- }
- return (bool)$wgReadOnly;
- }
-
- function wfReadOnlyReason() {
- global $wgReadOnly;
- wfReadOnly();
- return $wgReadOnly;
- }
-
- /**
- * Return a Language object from $langcode
- * @param $langcode Mixed: either:
- * - a Language object
- * - code of the language to get the message for, if it is
- * a valid code create a language for that language, if
- * it is a string but not a valid code then make a basic
- * language object
- * - a boolean: if it's false then use the current users
- * language (as a fallback for the old parameter
- * functionality), or if it is true then use the wikis
- * @return Language object
- */
- function wfGetLangObj( $langcode = false ) {
- # Identify which language to get or create a language object for.
- # Using is_object here due to Stub objects.
- if( is_object( $langcode ) ) {
- # Great, we already have the object (hopefully)!
- return $langcode;
- }
-
- global $wgContLang, $wgLanguageCode;
- if( $langcode === true || $langcode === $wgLanguageCode ) {
- # $langcode is the language code of the wikis content language object.
- # or it is a boolean and value is true
- return $wgContLang;
- }
-
- global $wgLang;
- if( $langcode === false || $langcode === $wgLang->getCode() ) {
- # $langcode is the language code of user language object.
- # or it was a boolean and value is false
- return $wgLang;
- }
-
- $validCodes = array_keys( Language::getLanguageNames() );
- if( in_array( $langcode, $validCodes ) ) {
- # $langcode corresponds to a valid language.
- return Language::factory( $langcode );
- }
-
- # $langcode is a string, but not a valid language code; use content language.
- wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
- return $wgContLang;
- }
-
- /**
- * Use this instead of $wgContLang, when working with user interface.
- * User interface is currently hard coded according to wiki content language
- * in many ways, especially regarding to text direction. There is lots stuff
- * to fix, hence this function to keep the old behaviour unless the global
- * $wgBetterDirectionality is enabled (or removed when everything works).
- */
- function wfUILang() {
- global $wgBetterDirectionality;
- return wfGetLangObj( !$wgBetterDirectionality );
- }
-
- /**
- * This is the new function for getting translated interface messages.
- * See the Message class for documentation how to use them.
- * The intention is that this function replaces all old wfMsg* functions.
- * @param $key \string Message key.
- * Varargs: normal message parameters.
- * @return \type{Message}
- * @since 1.17
- */
- function wfMessage( $key /*...*/) {
- $params = func_get_args();
- array_shift( $params );
- if ( isset( $params[0] ) && is_array( $params[0] ) ) {
- $params = $params[0];
- }
- return new Message( $key, $params );
- }
-
- /**
- * Get a message from anywhere, for the current user language.
- *
- * Use wfMsgForContent() instead if the message should NOT
- * change depending on the user preferences.
- *
- * @param $key String: lookup key for the message, usually
- * defined in languages/Language.php
- *
- * This function also takes extra optional parameters (not
- * shown in the function definition), which can be used to
- * insert variable text into the predefined message.
- */
- function wfMsg( $key ) {
- $args = func_get_args();
- array_shift( $args );
- return wfMsgReal( $key, $args, true );
- }
-
- /**
- * Same as above except doesn't transform the message
- */
- function wfMsgNoTrans( $key ) {
- $args = func_get_args();
- array_shift( $args );
- return wfMsgReal( $key, $args, true, false, false );
- }
-
- /**
- * Get a message from anywhere, for the current global language
- * set with $wgLanguageCode.
- *
- * Use this if the message should NOT change dependent on the
- * language set in the user's preferences. This is the case for
- * most text written into logs, as well as link targets (such as
- * the name of the copyright policy page). Link titles, on the
- * other hand, should be shown in the UI language.
- *
- * Note that MediaWiki allows users to change the user interface
- * language in their preferences, but a single installation
- * typically only contains content in one language.
- *
- * Be wary of this distinction: If you use wfMsg() where you should
- * use wfMsgForContent(), a user of the software may have to
- * customize potentially hundreds of messages in
- * order to, e.g., fix a link in every possible language.
- *
- * @param $key String: lookup key for the message, usually
- * defined in languages/Language.php
- */
- function wfMsgForContent( $key ) {
- global $wgForceUIMsgAsContentMsg;
- $args = func_get_args();
- array_shift( $args );
- $forcontent = true;
- if( is_array( $wgForceUIMsgAsContentMsg ) &&
- in_array( $key, $wgForceUIMsgAsContentMsg ) )
- {
- $forcontent = false;
- }
- return wfMsgReal( $key, $args, true, $forcontent );
- }
-
- /**
- * Same as above except doesn't transform the message
- */
- function wfMsgForContentNoTrans( $key ) {
- global $wgForceUIMsgAsContentMsg;
- $args = func_get_args();
- array_shift( $args );
- $forcontent = true;
- if( is_array( $wgForceUIMsgAsContentMsg ) &&
- in_array( $key, $wgForceUIMsgAsContentMsg ) )
- {
- $forcontent = false;
- }
- return wfMsgReal( $key, $args, true, $forcontent, false );
- }
-
- /**
- * Get a message from the language file, for the UI elements
- */
- function wfMsgNoDB( $key ) {
- $args = func_get_args();
- array_shift( $args );
- return wfMsgReal( $key, $args, false );
- }
-
- /**
- * Get a message from the language file, for the content
- */
- function wfMsgNoDBForContent( $key ) {
- global $wgForceUIMsgAsContentMsg;
- $args = func_get_args();
- array_shift( $args );
- $forcontent = true;
- if( is_array( $wgForceUIMsgAsContentMsg ) &&
- in_array( $key, $wgForceUIMsgAsContentMsg ) )
- {
- $forcontent = false;
- }
- return wfMsgReal( $key, $args, false, $forcontent );
- }
-
-
- /**
- * Really get a message
- * @param $key String: key to get.
- * @param $args
- * @param $useDB Boolean
- * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
- * @param $transform Boolean: Whether or not to transform the message.
- * @return String: the requested message.
- */
- function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
- wfProfileIn( __METHOD__ );
- $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
- $message = wfMsgReplaceArgs( $message, $args );
- wfProfileOut( __METHOD__ );
- return $message;
- }
-
- /**
- * This function provides the message source for messages to be edited which are *not* stored in the database.
- * @param $key String:
- */
- function wfMsgWeirdKey( $key ) {
- $source = wfMsgGetKey( $key, false, true, false );
- if ( wfEmptyMsg( $key, $source ) ) {
- return '';
- } else {
- return $source;
- }
- }
-
- /**
- * Fetch a message string value, but don't replace any keys yet.
- * @param $key String
- * @param $useDB Bool
- * @param $langCode String: Code of the language to get the message for, or
- * behaves as a content language switch if it is a boolean.
- * @param $transform Boolean: whether to parse magic words, etc.
- * @return string
- */
- function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
- global $wgMessageCache;
-
- wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
-
- if ( !is_object( $wgMessageCache ) ) {
- throw new MWException( 'Trying to get message before message cache is initialised' );
- }
-
- $message = $wgMessageCache->get( $key, $useDB, $langCode );
- if( $message === false ) {
- $message = '<' . htmlspecialchars( $key ) . '>';
- } elseif ( $transform ) {
- $message = $wgMessageCache->transform( $message );
- }
- return $message;
- }
-
- /**
- * Replace message parameter keys on the given formatted output.
- *
- * @param $message String
- * @param $args Array
- * @return string
- * @private
- */
- function wfMsgReplaceArgs( $message, $args ) {
- # Fix windows line-endings
- # Some messages are split with explode("\n", $msg)
- $message = str_replace( "\r", '', $message );
-
- // Replace arguments
- if ( count( $args ) ) {
- if ( is_array( $args[0] ) ) {
- $args = array_values( $args[0] );
- }
- $replacementKeys = array();
- foreach( $args as $n => $param ) {
- $replacementKeys['$' . ( $n + 1 )] = $param;
- }
- $message = strtr( $message, $replacementKeys );
- }
-
- return $message;
- }
-
- /**
- * Return an HTML-escaped version of a message.
- * Parameter replacements, if any, are done *after* the HTML-escaping,
- * so parameters may contain HTML (eg links or form controls). Be sure
- * to pre-escape them if you really do want plaintext, or just wrap
- * the whole thing in htmlspecialchars().
- *
- * @param $key String
- * @param string ... parameters
- * @return string
- */
- function wfMsgHtml( $key ) {
- $args = func_get_args();
- array_shift( $args );
- return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
- }
-
- /**
- * Return an HTML version of message
- * Parameter replacements, if any, are done *after* parsing the wiki-text message,
- * so parameters may contain HTML (eg links or form controls). Be sure
- * to pre-escape them if you really do want plaintext, or just wrap
- * the whole thing in htmlspecialchars().
- *
- * @param $key String
- * @param string ... parameters
- * @return string
- */
- function wfMsgWikiHtml( $key ) {
- global $wgOut;
- $args = func_get_args();
- array_shift( $args );
- return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
- }
-
- /**
- * Returns message in the requested format
- * @param $key String: key of the message
- * @param $options Array: processing rules. Can take the following options:
- * <i>parse</i>: parses wikitext to HTML
- * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
- * p's added by parser or tidy
- * <i>escape</i>: filters message through htmlspecialchars
- * <i>escapenoentities</i>: same, but allows entity references like   through
- * <i>replaceafter</i>: parameters are substituted after parsing or escaping
- * <i>parsemag</i>: transform the message using magic phrases
- * <i>content</i>: fetch message for content language instead of interface
- * Also can accept a single associative argument, of the form 'language' => 'xx':
- * <i>language</i>: Language object or language code to fetch message for
- * (overriden by <i>content</i>), its behaviour with parse, parseinline
- * and parsemag is undefined.
- * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
- */
- function wfMsgExt( $key, $options ) {
- global $wgOut;
-
- $args = func_get_args();
- array_shift( $args );
- array_shift( $args );
- $options = (array)$options;
-
- foreach( $options as $arrayKey => $option ) {
- if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
- # An unknown index, neither numeric nor "language"
- wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
- } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
- array( 'parse', 'parseinline', 'escape', 'escapenoentities',
- 'replaceafter', 'parsemag', 'content' ) ) ) {
- # A numeric index with unknown value
- wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
- }
- }
-
- if( in_array( 'content', $options, true ) ) {
- $forContent = true;
- $langCode = true;
- } elseif( array_key_exists( 'language', $options ) ) {
- $forContent = false;
- $langCode = wfGetLangObj( $options['language'] );
- } else {
- $forContent = false;
- $langCode = false;
- }
-
- $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
-
- if( !in_array( 'replaceafter', $options, true ) ) {
- $string = wfMsgReplaceArgs( $string, $args );
- }
-
- if( in_array( 'parse', $options, true ) ) {
- $string = $wgOut->parse( $string, true, !$forContent );
- } elseif ( in_array( 'parseinline', $options, true ) ) {
- $string = $wgOut->parse( $string, true, !$forContent );
- $m = array();
- if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
- $string = $m[1];
- }
- } elseif ( in_array( 'parsemag', $options, true ) ) {
- global $wgMessageCache;
- if ( isset( $wgMessageCache ) ) {
- $string = $wgMessageCache->transform( $string,
- !$forContent,
- is_object( $langCode ) ? $langCode : null );
- }
- }
-
- if ( in_array( 'escape', $options, true ) ) {
- $string = htmlspecialchars ( $string );
- } elseif ( in_array( 'escapenoentities', $options, true ) ) {
- $string = Sanitizer::escapeHtmlAllowEntities( $string );
- }
-
- if( in_array( 'replaceafter', $options, true ) ) {
- $string = wfMsgReplaceArgs( $string, $args );
- }
-
- return $string;
- }
-
-
- /**
- * Just like exit() but makes a note of it.
- * Commits open transactions except if the error parameter is set
- *
- * @deprecated Please return control to the caller or throw an exception. Will
- * be removed in 1.19.
- */
- function wfAbruptExit( $error = false ) {
- static $called = false;
- if ( $called ) {
- exit( -1 );
- }
- $called = true;
-
- wfDeprecated( __FUNCTION__ );
- $bt = wfDebugBacktrace();
- if( $bt ) {
- for( $i = 0; $i < count( $bt ); $i++ ) {
- $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
- $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
- wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
- }
- } else {
- wfDebug( "WARNING: Abrupt exit\n" );
- }
-
- wfLogProfilingData();
-
- if ( !$error ) {
- wfGetLB()->closeAll();
- }
- exit( -1 );
- }
-
- /**
- * @deprecated Please return control the caller or throw an exception. Will
- * be removed in 1.19.
- */
- function wfErrorExit() {
- wfDeprecated( __FUNCTION__ );
- wfAbruptExit( true );
- }
-
- /**
- * Print a simple message and die, returning nonzero to the shell if any.
- * Plain die() fails to return nonzero to the shell if you pass a string.
- * @param $msg String
- */
- function wfDie( $msg = '' ) {
- echo $msg;
- die( 1 );
- }
-
- /**
- * Throw a debugging exception. This function previously once exited the process,
- * but now throws an exception instead, with similar results.
- *
- * @param $msg String: message shown when dieing.
- */
- function wfDebugDieBacktrace( $msg = '' ) {
- throw new MWException( $msg );
- }
-
- /**
- * Fetch server name for use in error reporting etc.
- * Use real server name if available, so we know which machine
- * in a server farm generated the current page.
- * @return string
- */
- function wfHostname() {
- static $host;
- if ( is_null( $host ) ) {
- if ( function_exists( 'posix_uname' ) ) {
- // This function not present on Windows
- $uname = @posix_uname();
- } else {
- $uname = false;
- }
- if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
- $host = $uname['nodename'];
- } elseif ( getenv( 'COMPUTERNAME' ) ) {
- # Windows computer name
- $host = getenv( 'COMPUTERNAME' );
- } else {
- # This may be a virtual server.
- $host = $_SERVER['SERVER_NAME'];
- }
- }
- return $host;
- }
-
- /**
- * Returns a HTML comment with the elapsed time since request.
- * This method has no side effects.
- * @return string
- */
- function wfReportTime() {
- global $wgRequestTime, $wgShowHostnames;
-
- $now = wfTime();
- $elapsed = $now - $wgRequestTime;
-
- return $wgShowHostnames
- ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
- : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
- }
-
- /**
- * Safety wrapper for debug_backtrace().
- *
- * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
- * murky circumstances, which may be triggered in part by stub objects
- * or other fancy talkin'.
- *
- * Will return an empty array if Zend Optimizer is detected or if
- * debug_backtrace is disabled, otherwise the output from
- * debug_backtrace() (trimmed).
- *
- * @return array of backtrace information
- */
- function wfDebugBacktrace() {
- static $disabled = null;
-
- if( extension_loaded( 'Zend Optimizer' ) ) {
- wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
- return array();
- }
-
- if ( is_null( $disabled ) ) {
- $disabled = false;
- $functions = explode( ',', ini_get( 'disable_functions' ) );
- $functions = array_map( 'trim', $functions );
- $functions = array_map( 'strtolower', $functions );
- if ( in_array( 'debug_backtrace', $functions ) ) {
- wfDebug( "debug_backtrace is in disabled_functions\n" );
- $disabled = true;
- }
- }
- if ( $disabled ) {
- return array();
- }
-
- return array_slice( debug_backtrace(), 1 );
- }
-
- function wfBacktrace() {
- global $wgCommandLineMode;
-
- if ( $wgCommandLineMode ) {
- $msg = '';
- } else {
- $msg = "<ul>\n";
- }
- $backtrace = wfDebugBacktrace();
- foreach( $backtrace as $call ) {
- if( isset( $call['file'] ) ) {
- $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
- $file = $f[count( $f ) - 1];
- } else {
- $file = '-';
- }
- if( isset( $call['line'] ) ) {
- $line = $call['line'];
- } else {
- $line = '-';
- }
- if ( $wgCommandLineMode ) {
- $msg .= "$file line $line calls ";
- } else {
- $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
- }
- if( !empty( $call['class'] ) ) {
- $msg .= $call['class'] . '::';
- }
- $msg .= $call['function'] . '()';
-
- if ( $wgCommandLineMode ) {
- $msg .= "\n";
- } else {
- $msg .= "</li>\n";
- }
- }
- if ( $wgCommandLineMode ) {
- $msg .= "\n";
- } else {
- $msg .= "</ul>\n";
- }
-
- return $msg;
- }
-
-
- /* Some generic result counters, pulled out of SearchEngine */
-
-
- /**
- * @todo document
- */
- function wfShowingResults( $offset, $limit ) {
- global $wgLang;
- return wfMsgExt(
- 'showingresults',
- array( 'parseinline' ),
- $wgLang->formatNum( $limit ),
- $wgLang->formatNum( $offset + 1 )
- );
- }
-
- /**
- * @todo document
- */
- function wfShowingResultsNum( $offset, $limit, $num ) {
- global $wgLang;
- return wfMsgExt(
- 'showingresultsnum',
- array( 'parseinline' ),
- $wgLang->formatNum( $limit ),
- $wgLang->formatNum( $offset + 1 ),
- $wgLang->formatNum( $num )
- );
- }
-
- /**
- * Generate (prev x| next x) (20|50|100...) type links for paging
- * @param $offset String
- * @param $limit Integer
- * @param $link String
- * @param $query String: optional URL query parameter string
- * @param $atend Bool: optional param for specified if this is the last page
- */
- function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
- global $wgLang;
- $fmtLimit = $wgLang->formatNum( $limit );
- // FIXME: Why on earth this needs one message for the text and another one for tooltip??
- # Get prev/next link display text
- $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
- $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
- # Get prev/next link title text
- $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
- $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
- # Fetch the title object
- if( is_object( $link ) ) {
- $title =& $link;
- } else {
- $title = Title::newFromText( $link );
- if( is_null( $title ) ) {
- return false;
- }
- }
- # Make 'previous' link
- if( 0 != $offset ) {
- $po = $offset - $limit;
- $po = max( $po, 0 );
- $q = "limit={$limit}&offset={$po}";
- if( $query != '' ) {
- $q .= '&' . $query;
- }
- $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
- } else {
- $plink = $prev;
- }
- # Make 'next' link
- $no = $offset + $limit;
- $q = "limit={$limit}&offset={$no}";
- if( $query != '' ) {
- $q .= '&' . $query;
- }
- if( $atend ) {
- $nlink = $next;
- } else {
- $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
- }
- # Make links to set number of items per page
- $nums = $wgLang->pipeList( array(
- wfNumLink( $offset, 20, $title, $query ),
- wfNumLink( $offset, 50, $title, $query ),
- wfNumLink( $offset, 100, $title, $query ),
- wfNumLink( $offset, 250, $title, $query ),
- wfNumLink( $offset, 500, $title, $query )
- ) );
- return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
- }
-
- /**
- * Generate links for (20|50|100...) items-per-page links
- * @param $offset String
- * @param $limit Integer
- * @param $title Title
- * @param $query String: optional URL query parameter string
- */
- function wfNumLink( $offset, $limit, $title, $query = '' ) {
- global $wgLang;
- if( $query == '' ) {
- $q = '';
- } else {
- $q = $query.'&';
- }
- $q .= "limit={$limit}&offset={$offset}";
- $fmtLimit = $wgLang->formatNum( $limit );
- $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
- $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
- return $s;
- }
-
- /**
- * @todo document
- * @todo FIXME: we may want to blacklist some broken browsers
- *
- * @return bool Whereas client accept gzip compression
- */
- function wfClientAcceptsGzip() {
- static $result = null;
- if ( $result === null ) {
- $result = false;
- if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
- # FIXME: we may want to blacklist some broken browsers
- $m = array();
- if( preg_match(
- '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
- $_SERVER['HTTP_ACCEPT_ENCODING'],
- $m )
- )
- {
- if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
- $result = false;
- return $result;
- }
- wfDebug( " accepts gzip\n" );
- $result = true;
- }
- }
- }
- return $result;
- }
-
- /**
- * Obtain the offset and limit values from the request string;
- * used in special pages
- *
- * @param $deflimit Default limit if none supplied
- * @param $optionname Name of a user preference to check against
- * @return array
- *
- */
- function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
- global $wgRequest;
- return $wgRequest->getLimitOffset( $deflimit, $optionname );
- }
-
- /**
- * Escapes the given text so that it may be output using addWikiText()
- * without any linking, formatting, etc. making its way through. This
- * is achieved by substituting certain characters with HTML entities.
- * As required by the callers, <nowiki> is not used. It currently does
- * not filter out characters which have special meaning only at the
- * start of a line, such as "*".
- *
- * @param $text String: text to be escaped
- */
- function wfEscapeWikiText( $text ) {
- $text = str_replace(
- array( '[', '|', ']', '\'', 'ISBN ',
- 'RFC ', '://', "\n=", '{{', '}}' ),
- array( '[', '|', ']', ''', 'ISBN ',
- 'RFC ', '://', "\n=", '{{', '}}' ),
- htmlspecialchars( $text )
- );
- return $text;
- }
-
- /**
- * @todo document
- */
- function wfQuotedPrintable( $string, $charset = '' ) {
- # Probably incomplete; see RFC 2045
- if( empty( $charset ) ) {
- global $wgInputEncoding;
- $charset = $wgInputEncoding;
- }
- $charset = strtoupper( $charset );
- $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
-
- $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
- $replace = $illegal . '\t ?_';
- if( !preg_match( "/[$illegal]/", $string ) ) {
- return $string;
- }
- $out = "=?$charset?Q?";
- $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
- $out .= '?=';
- return $out;
- }
-
-
- /**
- * @todo document
- * @return float
- */
- function wfTime() {
- return microtime( true );
- }
-
- /**
- * Sets dest to source and returns the original value of dest
- * If source is NULL, it just returns the value, it doesn't set the variable
- */
- function wfSetVar( &$dest, $source ) {
- $temp = $dest;
- if ( !is_null( $source ) ) {
- $dest = $source;
- }
- return $temp;
- }
-
- /**
- * As for wfSetVar except setting a bit
- */
- function wfSetBit( &$dest, $bit, $state = true ) {
- $temp = (bool)( $dest & $bit );
- if ( !is_null( $state ) ) {
- if ( $state ) {
- $dest |= $bit;
- } else {
- $dest &= ~$bit;
- }
- }
- return $temp;
- }
-
- /**
- * This function takes two arrays as input, and returns a CGI-style string, e.g.
- * "days=7&limit=100". Options in the first array override options in the second.
- * Options set to "" will not be output.
- */
- function wfArrayToCGI( $array1, $array2 = null ) {
- if ( !is_null( $array2 ) ) {
- $array1 = $array1 + $array2;
- }
-
- $cgi = '';
- foreach ( $array1 as $key => $value ) {
- if ( $value !== '' ) {
- if ( $cgi != '' ) {
- $cgi .= '&';
- }
- if ( is_array( $value ) ) {
- $firstTime = true;
- foreach ( $value as $v ) {
- $cgi .= ( $firstTime ? '' : '&') .
- urlencode( $key . '[]' ) . '=' .
- urlencode( $v );
- $firstTime = false;
- }
- } else {
- if ( is_object( $value ) ) {
- $value = $value->__toString();
- }
- $cgi .= urlencode( $key ) . '=' .
- urlencode( $value );
- }
- }
- }
- return $cgi;
- }
-
- /**
- * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
- * its argument and returns the same string in array form. This allows compa-
- * tibility with legacy functions that accept raw query strings instead of nice
- * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
- * valid query strings, or it will explode.
- *
- * @param $query String: query string
- * @return array Array version of input
- */
- function wfCgiToArray( $query ) {
- if( isset( $query[0] ) && $query[0] == '?' ) {
- $query = substr( $query, 1 );
- }
- $bits = explode( '&', $query );
- $ret = array();
- foreach( $bits as $bit ) {
- if( $bit === '' ) {
- continue;
- }
- list( $key, $value ) = explode( '=', $bit );
- $key = urldecode( $key );
- $value = urldecode( $value );
- $ret[$key] = $value;
- }
- return $ret;
- }
-
- /**
- * Append a query string to an existing URL, which may or may not already
- * have query string parameters already. If so, they will be combined.
- *
- * @param $url String
- * @param $query Mixed: string or associative array
- * @return string
- */
- function wfAppendQuery( $url, $query ) {
- if ( is_array( $query ) ) {
- $query = wfArrayToCGI( $query );
- }
- if( $query != '' ) {
- if( false === strpos( $url, '?' ) ) {
- $url .= '?';
- } else {
- $url .= '&';
- }
- $url .= $query;
- }
- return $url;
- }
-
- /**
- * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
- * and $wgProto are correct.
- *
- * @todo this won't work with current-path-relative URLs
- * like "subdir/foo.html", etc.
- *
- * @param $url String: either fully-qualified or a local path + query
- * @return string Fully-qualified URL
- */
- function wfExpandUrl( $url ) {
- if( substr( $url, 0, 2 ) == '//' ) {
- global $wgProto;
- return $wgProto . ':' . $url;
- } elseif( substr( $url, 0, 1 ) == '/' ) {
- global $wgServer;
- return $wgServer . $url;
- } else {
- return $url;
- }
- }
-
- /**
- * Windows-compatible version of escapeshellarg()
- * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
- * function puts single quotes in regardless of OS.
- *
- * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
- * earlier distro releases of PHP)
- */
- function wfEscapeShellArg( ) {
- wfInitShellLocale();
-
- $args = func_get_args();
- $first = true;
- $retVal = '';
- foreach ( $args as $arg ) {
- if ( !$first ) {
- $retVal .= ' ';
- } else {
- $first = false;
- }
-
- if ( wfIsWindows() ) {
- // Escaping for an MSVC-style command line parser
- // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
- // Double the backslashes before any double quotes. Escape the double quotes.
- $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
- $arg = '';
- $iteration = 0;
- foreach ( $tokens as $token ) {
- if ( $iteration % 2 == 1 ) {
- // Delimiter, a double quote preceded by zero or more slashes
- $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
- } elseif ( $iteration % 4 == 2 ) {
- // ^ in $token will be outside quotes, need to be escaped
- $arg .= str_replace( '^', '^^', $token );
- } else { // $iteration % 4 == 0
- // ^ in $token will appear inside double quotes, so leave as is
- $arg .= $token;
- }
- $iteration++;
- }
- // Double the backslashes before the end of the string, because
- // we will soon add a quote
- $m = array();
- if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
- $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
- }
-
- // Add surrounding quotes
- $retVal .= '"' . $arg . '"';
- } else {
- $retVal .= escapeshellarg( $arg );
- }
- }
- return $retVal;
- }
-
- /**
- * wfMerge attempts to merge differences between three texts.
- * Returns true for a clean merge and false for failure or a conflict.
- */
- function wfMerge( $old, $mine, $yours, &$result ) {
- global $wgDiff3;
-
- # This check may also protect against code injection in
- # case of broken installations.
- wfSuppressWarnings();
- $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
- wfRestoreWarnings();
-
- if( !$haveDiff3 ) {
- wfDebug( "diff3 not found\n" );
- return false;
- }
-
- # Make temporary files
- $td = wfTempDir();
- $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
- $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
- $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
-
- fwrite( $oldtextFile, $old );
- fclose( $oldtextFile );
- fwrite( $mytextFile, $mine );
- fclose( $mytextFile );
- fwrite( $yourtextFile, $yours );
- fclose( $yourtextFile );
-
- # Check for a conflict
- $cmd = $wgDiff3 . ' -a --overlap-only ' .
- wfEscapeShellArg( $mytextName ) . ' ' .
- wfEscapeShellArg( $oldtextName ) . ' ' .
- wfEscapeShellArg( $yourtextName );
- $handle = popen( $cmd, 'r' );
-
- if( fgets( $handle, 1024 ) ) {
- $conflict = true;
- } else {
- $conflict = false;
- }
- pclose( $handle );
-
- # Merge differences
- $cmd = $wgDiff3 . ' -a -e --merge ' .
- wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
- $handle = popen( $cmd, 'r' );
- $result = '';
- do {
- $data = fread( $handle, 8192 );
- if ( strlen( $data ) == 0 ) {
- break;
- }
- $result .= $data;
- } while ( true );
- pclose( $handle );
- unlink( $mytextName );
- unlink( $oldtextName );
- unlink( $yourtextName );
-
- if ( $result === '' && $old !== '' && !$conflict ) {
- wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
- $conflict = true;
- }
- return !$conflict;
- }
-
- /**
- * Returns unified plain-text diff of two texts.
- * Useful for machine processing of diffs.
- * @param $before String: the text before the changes.
- * @param $after String: the text after the changes.
- * @param $params String: command-line options for the diff command.
- * @return String: unified diff of $before and $after
- */
- function wfDiff( $before, $after, $params = '-u' ) {
- if ( $before == $after ) {
- return '';
- }
-
- global $wgDiff;
- wfSuppressWarnings();
- $haveDiff = $wgDiff && file_exists( $wgDiff );
- wfRestoreWarnings();
-
- # This check may also protect against code injection in
- # case of broken installations.
- if( !$haveDiff ) {
- wfDebug( "diff executable not found\n" );
- $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
- $format = new UnifiedDiffFormatter();
- return $format->format( $diffs );
- }
-
- # Make temporary files
- $td = wfTempDir();
- $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
- $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
-
- fwrite( $oldtextFile, $before );
- fclose( $oldtextFile );
- fwrite( $newtextFile, $after );
- fclose( $newtextFile );
-
- // Get the diff of the two files
- $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
-
- $h = popen( $cmd, 'r' );
-
- $diff = '';
-
- do {
- $data = fread( $h, 8192 );
- if ( strlen( $data ) == 0 ) {
- break;
- }
- $diff .= $data;
- } while ( true );
-
- // Clean up
- pclose( $h );
- unlink( $oldtextName );
- unlink( $newtextName );
-
- // Kill the --- and +++ lines. They're not useful.
- $diff_lines = explode( "\n", $diff );
- if ( strpos( $diff_lines[0], '---' ) === 0 ) {
- unset( $diff_lines[0] );
- }
- if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
- unset( $diff_lines[1] );
- }
-
- $diff = implode( "\n", $diff_lines );
-
- return $diff;
- }
-
- /**
- * A wrapper around the PHP function var_export().
- * Either print it or add it to the regular output ($wgOut).
- *
- * @param $var A PHP variable to dump.
- */
- function wfVarDump( $var ) {
- global $wgOut;
- $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
- if ( headers_sent() || !@is_object( $wgOut ) ) {
- print $s;
- } else {
- $wgOut->addHTML( $s );
- }
- }
-
- /**
- * Provide a simple HTTP error.
- */
- function wfHttpError( $code, $label, $desc ) {
- global $wgOut;
- $wgOut->disable();
- header( "HTTP/1.0 $code $label" );
- header( "Status: $code $label" );
- $wgOut->sendCacheControl();
-
- header( 'Content-type: text/html; charset=utf-8' );
- print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
- '<html><head><title>' .
- htmlspecialchars( $label ) .
- '</title></head><body><h1>' .
- htmlspecialchars( $label ) .
- '</h1><p>' .
- nl2br( htmlspecialchars( $desc ) ) .
- "</p></body></html>\n";
- }
-
- /**
- * Clear away any user-level output buffers, discarding contents.
- *
- * Suitable for 'starting afresh', for instance when streaming
- * relatively large amounts of data without buffering, or wanting to
- * output image files without ob_gzhandler's compression.
- *
- * The optional $resetGzipEncoding parameter controls suppression of
- * the Content-Encoding header sent by ob_gzhandler; by default it
- * is left. See comments for wfClearOutputBuffers() for why it would
- * be used.
- *
- * Note that some PHP configuratiā¦
Large files files are truncated, but you can click here to view the full file