/**
* List of available modules: action name => module class
*/
- private static $Modules = array(
+ private static $Modules = [
'login' => 'ApiLogin',
'logout' => 'ApiLogout',
'createaccount' => 'ApiCreateAccount',
'revisiondelete' => 'ApiRevisionDelete',
'managetags' => 'ApiManageTags',
'tag' => 'ApiTag',
- );
+ 'mergehistory' => 'ApiMergeHistory',
+ ];
/**
* List of available formats: format name => format class
*/
- private static $Formats = array(
+ private static $Formats = [
'json' => 'ApiFormatJson',
'jsonfm' => 'ApiFormatJson',
'php' => 'ApiFormatPhp',
'xmlfm' => 'ApiFormatXml',
'rawfm' => 'ApiFormatJson',
'none' => 'ApiFormatNone',
- );
+ ];
// @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
/**
* 'params' => array ( $someVarToSubst ) ),
* );
*/
- private static $mRights = array(
- 'writeapi' => array(
+ private static $mRights = [
+ 'writeapi' => [
'msg' => 'right-writeapi',
- 'params' => array()
- ),
- 'apihighlimits' => array(
+ 'params' => []
+ ],
+ 'apihighlimits' => [
'msg' => 'api-help-right-apihighlimits',
- 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
- )
- );
+ 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
+ ]
+ ];
// @codingStandardsIgnoreEnd
/**
private $mInternalMode, $mSquidMaxage, $mModule;
private $mCacheMode = 'private';
- private $mCacheControl = array();
- private $mParamsUsed = array();
+ private $mCacheControl = [];
+ private $mParamsUsed = [];
/**
* Constructs an instance of ApiMain that utilizes the module and format specified by $request.
$this->mModuleMgr->addModules( self::$Formats, 'format' );
$this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
- Hooks::run( 'ApiMain::moduleManager', array( $this->mModuleMgr ) );
+ Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
$this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
$this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
* @param int $maxage
*/
public function setCacheMaxAge( $maxage ) {
- $this->setCacheControl( array(
+ $this->setCacheControl( [
'max-age' => $maxage,
's-maxage' => $maxage
- ) );
+ ] );
}
/**
* If this function is never called, then the default will be the private mode.
*/
public function setCacheMode( $mode ) {
- if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
+ if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
// Ignore for forwards-compatibility
ob_start();
$t = microtime( true );
+ $isError = false;
try {
$this->executeAction();
- $isError = false;
+ $this->logRequest( microtime( true ) - $t );
+
} catch ( Exception $e ) {
$this->handleException( $e );
+ $this->logRequest( microtime( true ) - $t, $e );
$isError = true;
}
- // Log the request whether or not there was an error
- $this->logRequest( microtime( true ) - $t );
-
// Commit DBs and send any related cookies and headers
MediaWiki::preOutputCommit( $this->getContext() );
}
// Allow extra cleanup and logging
- Hooks::run( 'ApiMain::onException', array( $this, $e ) );
+ Hooks::run( 'ApiMain::onException', [ $this, $e ] );
// Log it
if ( !( $e instanceof UsageException ) ) {
try {
$main = new self( RequestContext::getMain(), false );
$main->handleException( $e );
+ $main->logRequest( 0, $e );
} catch ( Exception $e2 ) {
// Nope, even that didn't work. Punt.
throw $e;
}
- // Log the request and reset cache headers
- $main->logRequest( 0 );
+ // Reset cache headers
$main->sendCacheHeaders( true );
ob_end_flush();
// Origin: header is a space-separated list of origins, check all of them
$originHeader = $request->getHeader( 'Origin' );
if ( $originHeader === false ) {
- $origins = array();
+ $origins = [];
} else {
$originHeader = trim( $originHeader );
$origins = preg_split( '/\s+/', $originHeader );
return true;
}
$requestedHeaders = explode( ',', $requestedHeaders );
- $allowedAuthorHeaders = array_flip( array(
+ $allowedAuthorHeaders = array_flip( [
/* simple headers (see spec) */
'accept',
'accept-language',
'origin',
/* MediaWiki whitelist */
'api-user-agent',
- ) );
+ ] );
foreach ( $requestedHeaders as $rHeader ) {
$rHeader = strtolower( trim( $rHeader ) );
if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
protected static function wildcardToRegex( $wildcard ) {
$wildcard = preg_quote( $wildcard, '/' );
$wildcard = str_replace(
- array( '\*', '\?' ),
- array( '.*?', '.' ),
+ [ '\*', '\?' ],
+ [ '.*?', '.' ],
$wildcard
);
}
/**
- * Replace the result data with the information about an exception.
- * Returns the error code
+ * Create an error message for the given exception.
+ *
+ * If the exception is a UsageException then
+ * UsageException::getMessageArray() will be called to create the message.
+ *
* @param Exception $e
- * @return string
+ * @return array ['code' => 'some string', 'info' => 'some other string']
+ * @since 1.27
*/
- protected function substituteResultWithError( $e ) {
- $result = $this->getResult();
- $config = $this->getConfig();
-
+ protected function errorMessageFromException( $e ) {
if ( $e instanceof UsageException ) {
// User entered incorrect parameters - generate error response
$errMessage = $e->getMessageArray();
- $link = wfExpandUrl( wfScript( 'api' ) );
- ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
} else {
// Something is seriously wrong
if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
$info = "Exception Caught: {$e->getMessage()}";
}
- $errMessage = array(
+ $errMessage = [
'code' => 'internal_api_error_' . get_class( $e ),
'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info,
- );
+ ];
+ }
+ return $errMessage;
+ }
+
+ /**
+ * Replace the result data with the information about an exception.
+ * Returns the error code
+ * @param Exception $e
+ * @return string
+ */
+ protected function substituteResultWithError( $e ) {
+ $result = $this->getResult();
+ $config = $this->getConfig();
+
+ $errMessage = $this->errorMessageFromException( $e );
+ if ( $e instanceof UsageException ) {
+ // User entered incorrect parameters - generate error response
+ $link = wfExpandUrl( wfScript( 'api' ) );
+ ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
+ } else {
+ // Something is seriously wrong
if ( $config->get( 'ShowExceptionDetails' ) ) {
ApiResult::setContentValue(
$errMessage,
}
// Remember all the warnings to re-add them later
- $warnings = $result->getResultData( array( 'warnings' ) );
+ $warnings = $result->getResultData( [ 'warnings' ] );
$result->reset();
// Re-add the id
if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
$servedby = $this->getParameter( 'servedby' );
if ( $servedby ) {
- $result->addValue( null, 'servedby', wfHostName() );
+ $result->addValue( null, 'servedby', wfHostname() );
}
}
}
if ( !isset( $moduleParams['token'] ) ) {
- $this->dieUsageMsg( array( 'missingparam', 'token' ) );
+ $this->dieUsageMsg( [ 'missingparam', 'token' ] );
}
if ( !$this->getConfig()->get( 'DebugAPI' ) &&
$return304 = false;
$ifNoneMatch = array_diff(
- $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: array(),
- array( '' )
+ $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
+ [ '' ]
);
if ( $ifNoneMatch ) {
- if ( $ifNoneMatch === array( '*' ) ) {
+ if ( $ifNoneMatch === [ '*' ] ) {
// API responses always "exist"
$etag = '*';
} else {
$lastMod = $module->getConditionalRequestData( 'last-modified' );
if ( $lastMod !== null ) {
// Mix in some MediaWiki modification times
- $modifiedTimes = array(
+ $modifiedTimes = [
'page' => $lastMod,
'user' => $this->getUser()->getTouched(),
'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
- );
+ ];
if ( $this->getConfig()->get( 'UseSquid' ) ) {
// T46570: the core page itself may not change, but resources might
$modifiedTimes['sepoch'] = wfTimestamp(
TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
);
}
- Hooks::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
+ Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] );
$lastMod = max( $modifiedTimes );
$return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
}
// Allow extensions to stop execution for arbitrary reasons.
$message = false;
- if ( !Hooks::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
+ if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
$this->dieUsageMsg( $message );
}
}
&& in_array( 'bot', $this->getUser()->getGroups() )
&& wfGetLB()->getServerCount() > 1
) {
- // Figure out how many servers have passed the lag threshold
- $numLagged = 0;
- $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
- foreach ( wfGetLB()->getLagTimes() as $lag ) {
- if ( $lag > $lagLimit ) {
- ++$numLagged;
- }
- }
- // If a majority of slaves are too lagged then disallow writes
- $slaveCount = wfGetLB()->getServerCount() - 1;
- if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
- $parsed = $this->parseMsg( array( 'readonlytext' ) );
- $this->dieUsage(
- $parsed['info'],
- $parsed['code'],
- /* http error */
- 0,
- array( 'readonlyreason' => "Waiting for $numLagged lagged database(s)" )
- );
+ $this->checkBotReadOnly();
+ }
+ }
+
+ /**
+ * Check whether we are readonly for bots
+ */
+ private function checkBotReadOnly() {
+ // Figure out how many servers have passed the lag threshold
+ $numLagged = 0;
+ $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
+ $laggedServers = [];
+ $loadBalancer = wfGetLB();
+ foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
+ if ( $lag > $lagLimit ) {
+ ++$numLagged;
+ $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
}
}
+
+ // If a majority of slaves are too lagged then disallow writes
+ $slaveCount = wfGetLB()->getServerCount() - 1;
+ if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
+ $laggedServers = join( ', ', $laggedServers );
+ wfDebugLog(
+ 'api-readonly',
+ "Api request failed as read only because the following DBs are lagged: $laggedServers"
+ );
+
+ $parsed = $this->parseMsg( [ 'readonlytext' ] );
+ $this->dieUsage(
+ $parsed['info'],
+ $parsed['code'],
+ /* http error */
+ 0,
+ [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
+ );
+ }
}
/**
if ( !$request->wasPosted() && $module->mustBePosted() ) {
// Module requires POST. GET request might still be allowed
// if $wgDebugApi is true, otherwise fail.
- $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
+ $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
}
// See if custom printer is used
$module = $this->setupModule();
$this->mModule = $module;
- $this->setRequestExpectations( $module );
+ if ( !$this->mInternalMode ) {
+ $this->setRequestExpectations( $module );
+ }
$this->checkExecutePermissions( $module );
// Execute
$module->execute();
- Hooks::run( 'APIAfterExecute', array( &$module ) );
+ Hooks::run( 'APIAfterExecute', [ &$module ] );
$this->reportUnusedParams();
/**
* Log the preceding request
* @param float $time Time in seconds
+ * @param Exception $e Exception caught while processing the request
*/
- protected function logRequest( $time ) {
+ protected function logRequest( $time, $e = null ) {
$request = $this->getRequest();
- $logCtx = array(
- 'dt' => date( 'c' ),
- 'client_ip' => $request->getIP(),
- 'user_agent' => $this->getUserAgent(),
+ $logCtx = [
+ 'ts' => time(),
+ 'ip' => $request->getIP(),
+ 'userAgent' => $this->getUserAgent(),
'wiki' => wfWikiID(),
- 'time_backend_ms' => round( $time * 1000 ),
- 'params' => array(),
- );
+ 'timeSpentBackend' => round( $time * 1000 ),
+ 'hadError' => $e !== null,
+ 'errorCodes' => [],
+ 'params' => [],
+ ];
+
+ if ( $e ) {
+ $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
+ }
// Construct space separated message for 'api' log channel
$msg = "API {$request->getMethod()} " .
wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
- " {$logCtx['client_ip']} " .
- "T={$logCtx['time_backend_ms']}ms";
+ " {$logCtx['ip']} " .
+ "T={$logCtx['timeSpentBackend']}ms";
foreach ( $this->getParamsUsed() as $name ) {
$value = $request->getVal( $name );
if ( !$this->mInternalMode ) {
// Printer has not yet executed; don't warn that its parameters are unused
$printerParams = array_map(
- array( $this->mPrinter, 'encodeParamName' ),
- array_keys( $this->mPrinter->getFinalParams() ?: array() )
+ [ $this->mPrinter, 'encodeParamName' ],
+ array_keys( $this->mPrinter->getFinalParams() ?: [] )
);
$unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
} else {
* @return array
*/
public function getAllowedParams() {
- return array(
- 'action' => array(
+ return [
+ 'action' => [
ApiBase::PARAM_DFLT => 'help',
ApiBase::PARAM_TYPE => 'submodule',
- ),
- 'format' => array(
+ ],
+ 'format' => [
ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
ApiBase::PARAM_TYPE => 'submodule',
- ),
- 'maxlag' => array(
+ ],
+ 'maxlag' => [
ApiBase::PARAM_TYPE => 'integer'
- ),
- 'smaxage' => array(
+ ],
+ 'smaxage' => [
ApiBase::PARAM_TYPE => 'integer',
ApiBase::PARAM_DFLT => 0
- ),
- 'maxage' => array(
+ ],
+ 'maxage' => [
ApiBase::PARAM_TYPE => 'integer',
ApiBase::PARAM_DFLT => 0
- ),
- 'assert' => array(
- ApiBase::PARAM_TYPE => array( 'user', 'bot' )
- ),
+ ],
+ 'assert' => [
+ ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
+ ],
'requestid' => null,
'servedby' => false,
'curtimestamp' => false,
'origin' => null,
- 'uselang' => array(
+ 'uselang' => [
ApiBase::PARAM_DFLT => 'user',
- ),
- );
+ ],
+ ];
}
/** @see ApiBase::getExamplesMessages() */
protected function getExamplesMessages() {
- return array(
+ return [
'action=help'
=> 'apihelp-help-example-main',
'action=help&recursivesubmodules=1'
=> 'apihelp-help-example-recursive',
- );
+ ];
}
public function modifyHelp( array &$help, array $options, array &$tocData ) {
// Wish PHP had an "array_insert_before". Instead, we have to manually
// reindex the array to get 'permissions' in the right place.
$oldHelp = $help;
- $help = array();
+ $help = [];
foreach ( $oldHelp as $k => $v ) {
if ( $k === 'submodules' ) {
$help['permissions'] = '';
// Fill 'permissions'
$help['permissions'] .= Html::openElement( 'div',
- array( 'class' => 'apihelp-block apihelp-permissions' ) );
+ [ 'class' => 'apihelp-block apihelp-permissions' ] );
$m = $this->msg( 'api-help-permissions' );
if ( !$m->isDisabled() ) {
- $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
+ $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
$m->numParams( count( self::$mRights ) )->parse()
);
}
$header = $this->msg( 'api-help-datatypes-header' )->parse();
$help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
- array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
- Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/datatypes' ) ) ) .
+ [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
+ Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
$header
);
$help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
if ( !isset( $tocData['main/datatypes'] ) ) {
$tocnumber[$level]++;
- $tocData['main/datatypes'] = array(
+ $tocData['main/datatypes'] = [
'toclevel' => count( $tocnumber ),
'level' => $level,
'anchor' => 'main/datatypes',
'line' => $header,
'number' => join( '.', $tocnumber ),
'index' => false,
- );
+ ];
}
$header = $this->msg( 'api-credits-header' )->parse();
$help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
- array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
- Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/credits' ) ) ) .
+ [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
+ Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
$header
);
$help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
if ( !isset( $tocData['main/credits'] ) ) {
$tocnumber[$level]++;
- $tocData['main/credits'] = array(
+ $tocData['main/credits'] = [
'toclevel' => count( $tocnumber ),
'level' => $level,
'anchor' => 'main/credits',
'line' => $header,
'number' => join( '.', $tocnumber ),
'index' => false,
- );
+ ];
}
}
}
str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
),
$cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
- array( $this, 'reallyMakeHelpMsg' )
+ [ $this, 'reallyMakeHelpMsg' ]
);
}
* @return array
*/
public function getMessageArray() {
- $result = array(
+ $result = [
'code' => $this->mCodestr,
'info' => $this->getMessage()
- );
+ ];
if ( is_array( $this->mExtraData ) ) {
$result = array_merge( $result, $this->mExtraData );
}