* PHP extensions may be included here.
*/
-if ( !function_exists( 'mb_substr' ) ) {
- /**
- * @codeCoverageIgnore
- * @see Fallback::mb_substr
- * @return string
- */
- function mb_substr( $str, $start, $count = 'end' ) {
- return Fallback::mb_substr( $str, $start, $count );
- }
-
- /**
- * @codeCoverageIgnore
- * @see Fallback::mb_substr_split_unicode
- * @return int
- */
- function mb_substr_split_unicode( $str, $splitPos ) {
- return Fallback::mb_substr_split_unicode( $str, $splitPos );
- }
-}
-
-if ( !function_exists( 'mb_strlen' ) ) {
- /**
- * @codeCoverageIgnore
- * @see Fallback::mb_strlen
- * @return int
- */
- function mb_strlen( $str, $enc = '' ) {
- return Fallback::mb_strlen( $str, $enc );
- }
-}
-
-if ( !function_exists( 'mb_strpos' ) ) {
- /**
- * @codeCoverageIgnore
- * @see Fallback::mb_strpos
- * @return int
- */
- function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
- return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
- }
-}
-
-if ( !function_exists( 'mb_strrpos' ) ) {
- /**
- * @codeCoverageIgnore
- * @see Fallback::mb_strrpos
- * @return int
- */
- function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
- return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
- }
-}
-
// hash_equals function only exists in PHP >= 5.6.0
// http://php.net/hash_equals
if ( !function_exists( 'hash_equals' ) ) {
*/
function wfMergeErrorArrays( /*...*/ ) {
$args = func_get_args();
- $out = array();
+ $out = [];
foreach ( $args as $errors ) {
foreach ( $errors as $params ) {
$originalParams = $params;
if ( $params[0] instanceof MessageSpecifier ) {
$msg = $params[0];
- $params = array_merge( array( $msg->getKey() ), $msg->getParams() );
+ $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
}
# @todo FIXME: Sometimes get nested arrays for $params,
# which leads to E_NOTICEs
* @return array
*/
function wfObjectToArray( $objOrArray, $recursive = true ) {
- $array = array();
+ $array = [];
if ( is_object( $objOrArray ) ) {
$objOrArray = get_object_vars( $objOrArray );
}
}
if ( is_null( $needle ) ) {
- $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' );
+ $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
) {
$s = urlencode( $s );
$s = str_ireplace(
$needle,
- array( ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ),
+ [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
$s
);
$query = substr( $query, 1 );
}
$bits = explode( '&', $query );
- $ret = array();
+ $ret = [];
foreach ( $bits as $bit ) {
if ( $bit === '' ) {
continue;
$temp = $value;
foreach ( $keys as $k ) {
$k = substr( $k, 0, -1 );
- $temp = array( $k => $temp );
+ $temp = [ $k => $temp ];
}
if ( isset( $ret[$key] ) ) {
$ret[$key] = array_merge( $ret[$key], $temp );
// Support old-style $wgUrlProtocols strings, for backwards compatibility
// with LocalSettings files from 1.5
if ( is_array( $wgUrlProtocols ) ) {
- $protocols = array();
+ $protocols = [];
foreach ( $wgUrlProtocols as $protocol ) {
// Filter out '//' if !$includeProtocolRelative
if ( $includeProtocolRelative || $protocol !== '//' ) {
}
if ( $prot == '' ) {
- return array( "http:$index", "https:$index" );
+ return [ "http:$index", "https:$index" ];
} else {
- return array( $index );
+ return [ $index ];
}
}
* - false: same as 'private'
* @param array $context Additional logging context data
*/
-function wfDebug( $text, $dest = 'all', array $context = array() ) {
+function wfDebug( $text, $dest = 'all', array $context = [] ) {
global $wgDebugRawPage, $wgDebugLogPrefix;
global $wgDebugTimestamps, $wgRequestTime;
* @param array $context Additional logging context data
*/
function wfDebugLog(
- $logGroup, $text, $dest = 'all', array $context = array()
+ $logGroup, $text, $dest = 'all', array $context = []
) {
$text = trim( $text );
* @param string $text Database error message.
* @param array $context Additional logging context data
*/
-function wfLogDBError( $text, array $context = array() ) {
+function wfLogDBError( $text, array $context = [] ) {
$logger = LoggerFactory::getInstance( 'wfLogDBError' );
$logger->error( trim( $text ), $context );
}
* @throws MWException
* @deprecated since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport
*/
-function wfErrorLog( $text, $file, array $context = array() ) {
+function wfErrorLog( $text, $file, array $context = [] ) {
wfDeprecated( __METHOD__, '1.25' );
$logger = LoggerFactory::getInstance( 'wfErrorLog' );
$context['destination'] = $file;
return;
}
- $ctx = array( 'elapsed' => $request->getElapsedTime() );
+ $ctx = [ 'elapsed' => $request->getElapsedTime() ];
if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
if ( is_array( $args[0] ) ) {
$args = array_values( $args[0] );
}
- $replacementKeys = array();
+ $replacementKeys = [];
foreach ( $args as $n => $param ) {
$replacementKeys['$' . ( $n + 1 )] = $param;
}
global $wgRequestTime, $wgShowHostnames;
$responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
- $reportVars = array( 'wgBackendResponseTime' => $responseTime );
+ $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
if ( $wgShowHostnames ) {
$reportVars['wgHostname'] = wfHostname();
}
}
}
if ( $disabled ) {
- return array();
+ return [];
}
- if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
+ if ( $limit ) {
return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
} else {
return array_slice( debug_backtrace(), 1 );
$result = false;
if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
# @todo FIXME: We may want to blacklist some broken browsers
- $m = array();
+ $m = [];
if ( preg_match(
'/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
$_SERVER['HTTP_ACCEPT_ENCODING'],
function wfEscapeWikiText( $text ) {
static $repl = null, $repl2 = null;
if ( $repl === null ) {
- $repl = array(
+ $repl = [
'"' => '"', '&' => '&', "'" => ''', '<' => '<',
'=' => '=', '>' => '>', '[' => '[', ']' => ']',
'{' => '{', '|' => '|', '}' => '}', ';' => ';',
"\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
"\n----" => "\n----", "\r----" => "\r----",
'__' => '__', '://' => '://',
- );
+ ];
// We have to catch everything "\s" matches in PCRE
- foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
+ foreach ( [ 'ISBN', 'RFC', 'PMID' ] as $magic ) {
$repl["$magic "] = "$magic ";
$repl["$magic\t"] = "$magic	";
$repl["$magic\r"] = "$magic ";
// And handle protocols that don't use "://"
global $wgUrlProtocols;
- $repl2 = array();
+ $repl2 = [];
foreach ( $wgUrlProtocols as $prot ) {
if ( substr( $prot, -1 ) === ':' ) {
$repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
}
}
- $repl2 = $repl2 ? '/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
+ $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
}
$text = substr( strtr( "\n$text", $repl ), 1 );
$text = preg_replace( $repl2, '$1:', $text );
function wfAcceptToPrefs( $accept, $def = '*/*' ) {
# No arg means accept anything (per HTTP spec)
if ( !$accept ) {
- return array( $def => 1.0 );
+ return [ $def => 1.0 ];
}
- $prefs = array();
+ $prefs = [];
$parts = explode( ',', $accept );
foreach ( $parts as $part ) {
# @todo FIXME: Doesn't deal with params like 'text/html; level=1'
$values = explode( ';', trim( $part ) );
- $match = array();
+ $match = [];
if ( count( $values ) == 1 ) {
$prefs[$values[0]] = 1.0;
} elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
if ( array_key_exists( $type, $avail ) ) {
return $type;
} else {
- $parts = explode( '/', $type );
- if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
- return $parts[0] . '/*';
+ $mainType = explode( '/', $type )[0];
+ if ( array_key_exists( "$mainType/*", $avail ) ) {
+ return "$mainType/*";
} elseif ( array_key_exists( '*/*', $avail ) ) {
return '*/*';
} else {
* XXX: generalize to negotiate other stuff
*/
function wfNegotiateType( $cprefs, $sprefs ) {
- $combine = array();
+ $combine = [];
foreach ( array_keys( $sprefs ) as $type ) {
- $parts = explode( '/', $type );
- if ( $parts[1] != '*' ) {
+ $subType = explode( '/', $type )[1];
+ if ( $subType != '*' ) {
$ckey = mimeTypeMatch( $type, $cprefs );
if ( $ckey ) {
$combine[$type] = $sprefs[$type] * $cprefs[$ckey];
}
foreach ( array_keys( $cprefs ) as $type ) {
- $parts = explode( '/', $type );
- if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
+ $subType = explode( '/', $type )[1];
+ if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
$skey = mimeTypeMatch( $type, $sprefs );
if ( $skey ) {
$combine[$type] = $sprefs[$skey] * $cprefs[$type];
return $wgTmpDirectory;
}
- $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
+ $tmpDir = array_map( "getenv", [ 'TMPDIR', 'TMP', 'TEMP' ] );
$tmpDir[] = sys_get_temp_dir();
$tmpDir[] = ini_get( 'upload_tmp_dir' );
return true;
}
- $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
+ $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
if ( is_null( $mode ) ) {
$mode = $wgDirectoryMode;
}
// Double the backslashes before the end of the string, because
// we will soon add a quote
- $m = array();
+ $m = [];
if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
$arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
}
*
* @return string Collected stdout as a string
*/
-function wfShellExec( $cmd, &$retval = null, $environ = array(),
- $limits = array(), $options = array()
+function wfShellExec( $cmd, &$retval = null, $environ = [],
+ $limits = [], $options = []
) {
global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
$wgMaxShellWallClockTime, $wgShellCgroup;
}
wfDebug( "wfShellExec: $cmd\n" );
- $desc = array(
- 0 => array( 'file', 'php://stdin', 'r' ),
- 1 => array( 'pipe', 'w' ),
- 2 => array( 'file', 'php://stderr', 'w' ) );
+ $desc = [
+ 0 => [ 'file', 'php://stdin', 'r' ],
+ 1 => [ 'pipe', 'w' ],
+ 2 => [ 'file', 'php://stderr', 'w' ] ];
if ( $useLogPipe ) {
- $desc[3] = array( 'pipe', 'w' );
+ $desc[3] = [ 'pipe', 'w' ];
}
$pipes = null;
$scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
return '';
}
$outBuffer = $logBuffer = '';
- $emptyArray = array();
+ $emptyArray = [];
$status = false;
$logMsg = false;
// Build a table mapping resource IDs to pipe FDs to work around a
// PHP 5.3 issue in which stream_select() does not preserve array keys
// <https://bugs.php.net/bug.php?id=53427>.
- $fds = array();
+ $fds = [];
foreach ( $pipes as $fd => $pipe ) {
$fds[(int)$pipe] = $fd;
}
* this overwrites the global wgMaxShell* limits.
* @return string Collected stdout and stderr as a string
*/
-function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
+function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
return wfShellExec( $cmd, $retval, $environ, $limits,
- array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
+ [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
}
/**
* 'wrapper': Path to a PHP wrapper to handle the maintenance script
* @return string
*/
-function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
+function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
global $wgPhpCli;
// Give site config file a chance to run the script in a wrapper.
// The caller may likely want to call wfBasename() on $script.
- Hooks::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
- $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
+ Hooks::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
+ $cmd = isset( $options['php'] ) ? [ $options['php'] ] : [ $wgPhpCli ];
if ( isset( $options['wrapper'] ) ) {
$cmd[] = $options['wrapper'];
}
$encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
}
- $matches = array();
+ $matches = [];
if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
return $matches[1];
} else {
return Wikimedia\base_convert( $input, $sourceBase, $destBase, $pad, $lowercase, $engine );
}
-/**
- * Check if there is sufficient entropy in php's built-in session generation
- *
- * @deprecated since 1.27, PHP's session generation isn't used with
- * MediaWiki\\Session\\SessionManager
- * @return bool True = there is sufficient entropy
- */
-function wfCheckEntropy() {
- wfDeprecated( __FUNCTION__, '1.27' );
- return (
- ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
- || ini_get( 'session.entropy_file' )
- )
- && intval( ini_get( 'session.entropy_length' ) ) >= 32;
-}
-
/**
* @deprecated since 1.27, PHP's session generation isn't used with
- * MediaWiki\\Session\\SessionManager
+ * MediaWiki\Session\SessionManager
*/
function wfFixSessionID() {
wfDeprecated( __FUNCTION__, '1.27' );
/**
* Reset the session id
*
- * @deprecated since 1.27, use MediaWiki\\Session\\SessionManager instead
+ * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead
* @since 1.22
*/
function wfResetSessionID() {
/**
* Initialise php session
*
- * @deprecated since 1.27, use MediaWiki\\Session\\SessionManager instead.
+ * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead.
* Generally, "using" SessionManager will be calling ->getSessionById() or
* ::getGlobalSession() (depending on whether you were passing $sessionId
* here), then calling $session->persist().
function wfSetupSession( $sessionId = false ) {
wfDeprecated( __FUNCTION__, '1.27' );
- // If they're calling this, they probably want our session management even
- // if NO_SESSION was set for Setup.php.
- if ( !MediaWiki\Session\PHPSessionHandler::isInstalled() ) {
- MediaWiki\Session\PHPSessionHandler::install( SessionManager::singleton() );
- }
-
if ( $sessionId ) {
session_id( $sessionId );
}
*/
function wfMemcKey( /*...*/ ) {
return call_user_func_array(
- array( ObjectCache::getLocalClusterInstance(), 'makeKey' ),
+ [ ObjectCache::getLocalClusterInstance(), 'makeKey' ],
func_get_args()
);
}
$args = array_slice( func_get_args(), 2 );
$keyspace = $prefix ? "$db-$prefix" : $db;
return call_user_func_array(
- array( ObjectCache::getLocalClusterInstance(), 'makeKeyInternal' ),
- array( $keyspace, $args )
+ [ ObjectCache::getLocalClusterInstance(), 'makeKeyInternal' ],
+ [ $keyspace, $args ]
);
}
*/
function wfGlobalCacheKey( /*...*/ ) {
return call_user_func_array(
- array( ObjectCache::getLocalClusterInstance(), 'makeGlobalKey' ),
+ [ ObjectCache::getLocalClusterInstance(), 'makeGlobalKey' ],
func_get_args()
);
}
*
* @return DatabaseBase
*/
-function wfGetDB( $db, $groups = array(), $wiki = false ) {
+function wfGetDB( $db, $groups = [], $wiki = false ) {
return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
}
* @param array $options Associative array of options (see RepoGroup::findFile)
* @return File|bool File, or false if the file does not exist
*/
-function wfFindFile( $title, $options = array() ) {
+function wfFindFile( $title, $options = [] ) {
return RepoGroup::singleton()->findFile( $title, $options );
}
}
try {
- wfGetLBFactory()->waitForReplication( array(
+ wfGetLBFactory()->waitForReplication( [
'wiki' => $wiki,
'cluster' => $cluster,
'timeout' => $timeout,
// B/C: first argument used to be "max seconds of lag"; ignore such values
'ifWritesSince' => ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null
- ) );
+ ] );
} catch ( DBReplicationWaitError $e ) {
return false;
}
*/
function wfBCP47( $code ) {
$codeSegment = explode( '-', $code );
- $codeBCP = array();
+ $codeBCP = [];
foreach ( $codeSegment as $segNo => $seg ) {
// when previous segment is x, it is a private segment and should be lc
if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
* @return bool True if no handler aborted the hook
* @deprecated 1.25 - use Hooks::run
*/
-function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
+function wfRunHooks( $event, array $args = [], $deprecatedVersion = null ) {
return Hooks::run( $event, $args, $deprecatedVersion );
}
# Run the extension hook
$bad = false;
- if ( !Hooks::run( 'BadImage', array( $name, &$bad ) ) ) {
+ if ( !Hooks::run( 'BadImage', [ $name, &$bad ] ) ) {
return $bad;
}
$blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
}
# Build the list now
- $badImages = array();
+ $badImages = [];
$lines = explode( "\n", $blacklist );
foreach ( $lines as $line ) {
# List items only
}
# Find all links
- $m = array();
+ $m = [];
if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
continue;
}
- $exceptions = array();
+ $exceptions = [];
$imageDBkey = false;
foreach ( $m[1] as $i => $titleText ) {
$title = Title::newFromText( $titleText );
*/
function wfCanIPUseHTTPS( $ip ) {
$canDo = true;
- Hooks::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
+ Hooks::run( 'CanIPUseHTTPS', [ $ip, &$canDo ] );
return !!$canDo;
}
* @since 1.25
*/
function wfIsInfinity( $str ) {
- $infinityValues = array( 'infinite', 'indefinite', 'infinity', 'never' );
+ $infinityValues = [ 'infinite', 'indefinite', 'infinity', 'never' ];
return in_array( $str, $infinityValues );
}
function wfThumbIsStandard( File $file, array $params ) {
global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
- $multipliers = array( 1 );
+ $multipliers = [ 1 ];
if ( $wgResponsiveImages ) {
// These available sizes are hardcoded currently elsewhere in MediaWiki.
// @see Linker::processResponsiveImages
return false;
}
- $basicParams = array();
+ $basicParams = [];
if ( isset( $params['page'] ) ) {
$basicParams['page'] = $params['page'];
}
- $thumbLimits = array();
- $imageLimits = array();
+ $thumbLimits = [];
+ $imageLimits = [];
// Expand limits to account for multipliers
foreach ( $multipliers as $multiplier ) {
$thumbLimits = array_merge( $thumbLimits, array_map(
);
$imageLimits = array_merge( $imageLimits, array_map(
function ( $pair ) use ( $multiplier ) {
- return array(
+ return [
round( $pair[0] * $multiplier ),
round( $pair[1] * $multiplier ),
- );
+ ];
}, $wgImageLimits )
);
}
// Check if the width matches one of $wgThumbLimits
if ( in_array( $params['width'], $thumbLimits ) ) {
- $normalParams = $basicParams + array( 'width' => $params['width'] );
+ $normalParams = $basicParams + [ 'width' => $params['width'] ];
// Append any default values to the map (e.g. "lossy", "lossless", ...)
$handler->normaliseParams( $file, $normalParams );
} else {
// If not, then check if the width matchs one of $wgImageLimits
$match = false;
foreach ( $imageLimits as $pair ) {
- $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
+ $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
// Decide whether the thumbnail should be scaled on width or height.
// Also append any default values to the map (e.g. "lossy", "lossless", ...)
$handler->normaliseParams( $file, $normalParams );