132 'msg' =>
'right-writeapi',
136 'msg' =>
'api-help-right-apihighlimits',
190 parent::__construct( $this, $this->mInternalMode ?
'main_int' :
'main' );
194 if ( !$this->mInternalMode ) {
197 $originHeader =
$request->getHeader(
'Origin' );
198 if ( $originHeader ===
false ) {
201 $originHeader = trim( $originHeader );
202 $origins = preg_split(
'/\s+/', $originHeader );
204 $sessionCookies = array_intersect(
205 array_keys( $_COOKIE ),
206 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
208 if ( $origins && $sessionCookies && (
209 count( $origins ) !== 1 || !self::matchOrigin(
211 $config->get(
'CrossSiteAJAXdomains' ),
212 $config->get(
'CrossSiteAJAXdomainExceptions' )
215 LoggerFactory::getInstance(
'cors' )->warning(
216 'Non-whitelisted CORS request with session cookies', [
217 'origin' => $originHeader,
218 'cookies' => $sessionCookies,
230 wfDebug(
"API: stripping user credentials when the same-origin policy is not applied\n" );
231 $wgUser =
new User();
233 $request->response()->header(
'MediaWiki-Login-Suppressed: true' );
241 $uselang =
$request->getVal(
'uselang', self::API_DEFAULT_USELANG );
242 if ( $uselang ===
'user' ) {
246 if ( $uselang ===
'content' ) {
247 $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
251 if ( !$this->mInternalMode ) {
260 $errorFormat =
$request->getVal(
'errorformat',
'bc' );
261 $errorLangCode =
$request->getVal(
'errorlang',
'uselang' );
262 $errorsUseDB =
$request->getCheck(
'errorsuselocal' );
263 if ( in_array( $errorFormat, [
'plaintext',
'wikitext',
'html',
'raw',
'none' ],
true ) ) {
264 if ( $errorLangCode ===
'uselang' ) {
266 } elseif ( $errorLangCode ===
'content' ) {
267 $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
273 $this->mResult, $errorLang, $errorFormat, $errorsUseDB
281 $this->mModuleMgr->addModules( self::$Modules,
'action' );
282 $this->mModuleMgr->addModules( $config->get(
'APIModules' ),
'action' );
283 $this->mModuleMgr->addModules( self::$Formats,
'format' );
284 $this->mModuleMgr->addModules( $config->get(
'APIFormatModules' ),
'format' );
286 Hooks::run(
'ApiMain::moduleManager', [ $this->mModuleMgr ] );
288 $this->mContinuationManager =
null;
289 $this->mEnableWrite = $enableWrite;
291 $this->mSquidMaxage = -1;
292 $this->mCommit =
false;
330 if (
$request->getVal(
'origin' ) ===
'*' ) {
337 if (
$request->getHeader(
'Treat-as-Untrusted' ) !==
false ) {
368 if ( $manager !==
null && $this->mContinuationManager !==
null ) {
370 __METHOD__ .
': tried to set manager from ' . $manager->getSource() .
371 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
374 $this->mContinuationManager = $manager;
402 'max-age' => $maxage,
403 's-maxage' => $maxage
433 if ( !in_array( $mode, [
'private',
'public',
'anon-public-user-private' ] ) ) {
434 wfDebug( __METHOD__ .
": unrecognised cache mode \"$mode\"\n" );
442 if ( $mode !==
'private' ) {
443 wfDebug( __METHOD__ .
": ignoring request for $mode cache mode, private wiki\n" );
449 if ( $mode ===
'public' && $this->
getParameter(
'uselang' ) ===
'user' ) {
454 wfDebug( __METHOD__ .
": downgrading cache mode 'public' to " .
455 "'anon-public-user-private' due to uselang=user\n" );
456 $mode =
'anon-public-user-private';
459 wfDebug( __METHOD__ .
": setting cache mode $mode\n" );
460 $this->mCacheMode = $mode;
485 $printer = $this->mModuleMgr->getModule( $format,
'format',
true );
486 if ( $printer ===
null ) {
499 if ( $this->mInternalMode ) {
519 if ( $this->
getRequest()->getMethod() ===
'OPTIONS' ) {
525 $obLevel = ob_get_level();
528 $t = microtime(
true );
532 $runTime = microtime(
true ) -
$t;
534 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
535 'api.' . $this->mModule->getModuleName() .
'.executeTiming', 1000 * $runTime
541 }
catch ( Throwable $e ) {
556 while ( ob_get_level() > $obLevel ) {
587 $headerStr =
'MediaWiki-API-Error: ' . implode(
', ', $errCodes );
599 }
catch ( ApiUsageException $ex ) {
603 $this->
addWarning(
'apiwarn-errorprinterfailed' );
606 $this->mPrinter->addWarning( $error );
610 }
catch ( Throwable $ex2 ) {
617 $this->mPrinter =
null;
619 $this->mPrinter->forceDefaultParams();
620 if (
$e->getCode() ) {
642 $main->handleException(
$e );
643 $main->logRequest( 0,
$e );
647 }
catch ( Throwable $e2 ) {
653 $main->sendCacheHeaders(
true );
674 if ( $originParam ===
null ) {
682 $matchedOrigin =
false;
683 $allowTiming =
false;
686 if ( $originParam ===
'*' ) {
692 $matchedOrigin =
true;
694 $allowCredentials =
'false';
700 $originHeader =
$request->getHeader(
'Origin' );
701 if ( $originHeader ===
false ) {
704 $originHeader = trim( $originHeader );
705 $origins = preg_split(
'/\s+/', $originHeader );
708 if ( !in_array( $originParam, $origins ) ) {
712 $response->header(
'Cache-Control: no-cache' );
713 echo
"'origin' parameter does not match Origin header\n";
719 $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
721 $config->get(
'CrossSiteAJAXdomains' ),
722 $config->get(
'CrossSiteAJAXdomainExceptions' )
725 $allowOrigin = $originHeader;
726 $allowCredentials =
'true';
727 $allowTiming = $originHeader;
730 if ( $matchedOrigin ) {
731 $requestedMethod =
$request->getHeader(
'Access-Control-Request-Method' );
732 $preflight =
$request->getMethod() ===
'OPTIONS' && $requestedMethod !==
false;
735 if ( $requestedMethod !==
'POST' && $requestedMethod !==
'GET' ) {
737 $response->header(
'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
741 $requestedHeaders =
$request->getHeader(
'Access-Control-Request-Headers' );
742 if ( $requestedHeaders !==
false ) {
743 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
744 $response->header(
'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
747 $response->header(
'Access-Control-Allow-Headers: ' . $requestedHeaders );
751 $response->header(
'Access-Control-Allow-Methods: POST, GET' );
752 } elseif (
$request->getMethod() !==
'POST' &&
$request->getMethod() !==
'GET' ) {
755 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request' 760 $response->header(
"Access-Control-Allow-Origin: $allowOrigin" );
761 $response->header(
"Access-Control-Allow-Credentials: $allowCredentials" );
763 if ( $allowTiming !==
false ) {
764 $response->header(
"Timing-Allow-Origin: $allowTiming" );
769 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, ' 770 .
'MediaWiki-Login-Suppressed' 774 $response->header(
'MediaWiki-CORS-Rejection: Origin mismatch' );
778 $this->
getOutput()->addVaryHeader(
'Origin' );
793 foreach ( $rules
as $rule ) {
794 if ( preg_match( self::wildcardToRegex( $rule ),
$value ) ) {
796 foreach ( $exceptions
as $exc ) {
797 if ( preg_match( self::wildcardToRegex( $exc ),
$value ) ) {
817 if ( trim( $requestedHeaders ) ===
'' ) {
820 $requestedHeaders = explode(
',', $requestedHeaders );
821 $allowedAuthorHeaders = array_flip( [
835 foreach ( $requestedHeaders
as $rHeader ) {
836 $rHeader = strtolower( trim( $rHeader ) );
837 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
838 LoggerFactory::getInstance(
'api-warning' )->warning(
839 'CORS preflight failed on requested header: {header}', [
858 $wildcard = preg_quote( $wildcard,
'/' );
859 $wildcard = str_replace(
865 return "/^https?:\/\/$wildcard$/";
877 $out->addVaryHeader(
'Treat-as-Untrusted' );
881 if ( $config->get(
'VaryOnXFP' ) ) {
882 $out->addVaryHeader(
'X-Forwarded-Proto' );
885 if ( !$isError && $this->mModule &&
888 $etag = $this->mModule->getConditionalRequestData(
'etag' );
889 if ( $etag !==
null ) {
892 $lastMod = $this->mModule->getConditionalRequestData(
'last-modified' );
893 if ( $lastMod !==
null ) {
905 if ( isset( $this->mCacheControl[
'max-age'] ) ) {
906 $maxage = $this->mCacheControl[
'max-age'];
907 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
908 $this->mCacheMode !==
'private' 912 $privateCache =
'private, must-revalidate, max-age=' . $maxage;
914 if ( $this->mCacheMode ==
'private' ) {
915 $response->header(
"Cache-Control: $privateCache" );
919 $useKeyHeader = $config->get(
'UseKeyHeader' );
920 if ( $this->mCacheMode ==
'anon-public-user-private' ) {
921 $out->addVaryHeader(
'Cookie' );
923 if ( $useKeyHeader ) {
925 if (
$out->haveCacheVaryCookies() ) {
927 $response->header(
"Cache-Control: $privateCache" );
931 } elseif (
MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
934 $response->header(
"Cache-Control: $privateCache" );
942 if ( $useKeyHeader ) {
947 if ( !isset( $this->mCacheControl[
's-maxage'] ) ) {
948 $this->mCacheControl[
's-maxage'] = $this->
getParameter(
'smaxage' );
950 if ( !isset( $this->mCacheControl[
'max-age'] ) ) {
951 $this->mCacheControl[
'max-age'] = $this->
getParameter(
'maxage' );
954 if ( !$this->mCacheControl[
's-maxage'] && !$this->mCacheControl[
'max-age'] ) {
958 $response->header(
"Cache-Control: $privateCache" );
963 $this->mCacheControl[
'public'] =
true;
966 $maxAge = min( $this->mCacheControl[
's-maxage'], $this->mCacheControl[
'max-age'] );
967 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
974 if ( is_bool(
$value ) ) {
976 $ccHeader .= $separator .
$name;
980 $ccHeader .= $separator .
"$name=$value";
985 $response->header(
"Cache-Control: $ccHeader" );
992 if ( !isset( $this->mPrinter ) ) {
994 if ( !$this->mModuleMgr->isDefined(
$value,
'format' ) ) {
995 $value = self::API_DEFAULT_FORMAT;
1002 if ( !$this->mPrinter->canPrintErrors() ) {
1025 foreach (
$e->getStatusValue()->getErrorsByType(
$type )
as $error ) {
1028 } elseif (
$type !==
'error' ) {
1034 $class = preg_replace(
'#^Wikimedia\\\Rdbms\\\#',
'', get_class(
$e ) );
1035 $code =
'internal_api_error_' . $class;
1036 $data = [
'errorclass' => get_class(
$e ) ];
1037 if ( $config->get(
'ShowExceptionDetails' ) ) {
1039 $msg =
$e->getMessageObject();
1067 $errors =
$result->getResultData( [
'errors' ] );
1068 $warnings =
$result->getResultData( [
'warnings' ] );
1070 if ( $warnings !==
null ) {
1073 if ( $errors !==
null ) {
1077 foreach ( $errors
as $error ) {
1078 if ( isset( $error[
'code'] ) ) {
1079 $errorCodes[$error[
'code']] =
true;
1088 $errorCodes[$msg->getApiCode()] =
true;
1090 LoggerFactory::getInstance(
'api-warning' )->error(
'Invalid API error code "{code}"', [
1091 'code' => $msg->getApiCode(),
1094 $errorCodes[
'<invalid-code>'] =
true;
1096 $formatter->addError( $modulePath, $msg );
1099 $formatter->addWarning( $modulePath, $msg );
1105 $path = [
'error' ];
1115 $this->
msg(
'api-usage-docref',
$link )->inLanguage( $formatter->getLanguage() )->
text()
1117 . $this->
msg(
'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->
text()
1121 if ( $config->get(
'ShowExceptionDetails' ) ) {
1125 $this->
msg(
'api-exception-trace',
1130 )->inLanguage( $formatter->getLanguage() )->
text()
1138 return array_keys( $errorCodes );
1150 if ( $requestid !==
null ) {
1154 if ( $this->
getConfig()->
get(
'ShowHostnames' ) && (
1155 in_array(
'servedby', $force,
true ) || $this->
getParameter(
'servedby' )
1181 $this->mAction =
$params[
'action'];
1194 $module = $this->mModuleMgr->getModule( $this->mAction,
'action' );
1195 if ( $module ===
null ) {
1199 [
'apierror-unknownaction',
wfEscapeWikiText( $this->mAction ) ],
'unknown_action' 1203 $moduleParams = $module->extractRequestParams();
1206 if ( $module->needsToken() ===
true ) {
1208 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1209 'See documentation for ApiBase::needsToken for details.' 1212 if ( $module->needsToken() ) {
1213 if ( !$module->mustBePosted() ) {
1215 "Module '{$module->getModuleName()}' must require POST to use tokens." 1219 if ( !isset( $moduleParams[
'token'] ) ) {
1222 $module->dieWithError( [
'apierror-missingparam',
'token' ] );
1226 $module->requirePostedParameters( [
'token' ] );
1228 if ( !$module->validateToken( $moduleParams[
'token'], $moduleParams ) ) {
1229 $module->dieWithError(
'apierror-badtoken' );
1240 $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1242 'host' => $dbLag[0],
1247 $jobQueueLagFactor = $this->
getConfig()->get(
'JobQueueIncludeInMaxLagFactor' );
1248 if ( $jobQueueLagFactor ) {
1251 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1252 if ( $jobQueueLag > $lagInfo[
'lag'] ) {
1255 'lag' => $jobQueueLag,
1256 'type' =>
'jobqueue',
1257 'jobs' => $totalJobs,
1274 if ( $module->shouldCheckMaxlag() && isset(
$params[
'maxlag'] ) ) {
1277 if ( $lagInfo[
'lag'] > $maxLag ) {
1280 $response->header(
'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1281 $response->header(
'X-Database-Lag: ' . intval( $lagInfo[
'lag'] ) );
1283 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1285 [
'apierror-maxlag', $lagInfo[
'lag'], $lagInfo[
'host'] ],
1291 $this->
dieWithError( [
'apierror-maxlag-generic', $lagInfo[
'lag'] ],
'maxlag', $lagInfo );
1320 if ( $this->mInternalMode ) {
1325 if ( $this->
getRequest()->getMethod() !==
'GET' && $this->
getRequest()->getMethod() !==
'HEAD' ) {
1332 $ifNoneMatch = array_diff(
1336 if ( $ifNoneMatch ) {
1337 if ( $ifNoneMatch === [
'*' ] ) {
1341 $etag = $module->getConditionalRequestData(
'etag' );
1344 if ( $ifNoneMatch && $etag !==
null ) {
1345 $test = substr( $etag, 0, 2 ) ===
'W/' ? substr( $etag, 2 ) : $etag;
1346 $match = array_map(
function (
$s ) {
1347 return substr(
$s, 0, 2 ) ===
'W/' ? substr(
$s, 2 ) :
$s;
1349 $return304 = in_array( $test, $match,
true );
1356 $i = strpos(
$value,
';' );
1357 if ( $i !==
false ) {
1366 $ts->getTimestamp( TS_RFC2822 ) ===
$value ||
1368 $ts->format(
'l, d-M-y H:i:s' ) .
' GMT' ===
$value ||
1370 $ts->format(
'D M j H:i:s Y' ) ===
$value ||
1371 $ts->format(
'D M j H:i:s Y' ) ===
$value 1373 $lastMod = $module->getConditionalRequestData(
'last-modified' );
1374 if ( $lastMod !==
null ) {
1378 'user' => $this->
getUser()->getTouched(),
1379 'epoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1381 if ( $this->
getConfig()->
get(
'UseSquid' ) ) {
1384 TS_MW, time() - $this->
getConfig()->
get(
'SquidMaxage' )
1388 $lastMod = max( $modifiedTimes );
1389 $return304 =
wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1392 }
catch ( TimestampException
$e ) {
1399 $this->
getRequest()->response()->statusHeader( 304 );
1402 Wikimedia\suppressWarnings();
1403 ini_set(
'zlib.output_compression', 0 );
1404 Wikimedia\restoreWarnings();
1420 !
$user->isAllowed(
'read' )
1425 if ( $module->isWriteMode() ) {
1426 if ( !$this->mEnableWrite ) {
1428 } elseif ( !
$user->isAllowed(
'writeapi' ) ) {
1430 } elseif ( $this->
getRequest()->getHeader(
'Promise-Non-Write-API-Action' ) ) {
1431 $this->
dieWithError(
'apierror-promised-nonwrite-api' );
1438 $message =
'hookaborted';
1439 if ( !
Hooks::run(
'ApiCheckCanExecute', [ $module,
$user, &$message ] ) ) {
1453 if ( $module->isWriteMode()
1455 && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1467 $lagLimit = $this->
getConfig()->get(
'APIMaxLagThreshold' );
1468 $laggedServers = [];
1469 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1470 foreach ( $loadBalancer->getLagTimes()
as $serverIndex => $lag ) {
1471 if ( $lag > $lagLimit ) {
1473 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) .
" ({$lag}s)";
1478 $replicaCount = $loadBalancer->getServerCount() - 1;
1479 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1480 $laggedServers = implode(
', ', $laggedServers );
1483 "Api request failed as read only because the following DBs are lagged: $laggedServers" 1485 LoggerFactory::getInstance(
'api-warning' )->warning(
1486 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1487 'laggeddbs' => $laggedServers,
1494 [
'readonlyreason' =>
"Waiting for $numLagged lagged database(s)" ]
1504 if ( isset(
$params[
'assert'] ) ) {
1506 switch (
$params[
'assert'] ) {
1508 if (
$user->isAnon() ) {
1513 if ( !
$user->isAllowed(
'bot' ) ) {
1519 if ( isset(
$params[
'assertuser'] ) ) {
1521 if ( !$assertUser || !$this->
getUser()->equals( $assertUser ) ) {
1535 $validMethods = [
'GET',
'HEAD',
'POST',
'OPTIONS' ];
1538 if ( !in_array(
$request->getMethod(), $validMethods ) ) {
1542 if ( !
$request->wasPosted() && $module->mustBePosted() ) {
1549 $this->mPrinter = $module->getCustomPrinter();
1550 if ( is_null( $this->mPrinter ) ) {
1555 if (
$request->getProtocol() ===
'http' && (
1556 $request->getSession()->shouldForceHTTPS() ||
1557 ( $this->
getUser()->isLoggedIn() &&
1558 $this->
getUser()->requiresHTTPS() )
1560 $this->
addDeprecation(
'apiwarn-deprecation-httpsexpected',
'https-expected' );
1575 $this->mModule = $module;
1577 if ( !$this->mInternalMode ) {
1591 if ( !$this->mInternalMode ) {
1597 Hooks::run(
'APIAfterExecute', [ &$module ] );
1601 if ( !$this->mInternalMode ) {
1615 $limits = $this->
getConfig()->get(
'TrxProfilerLimits' );
1617 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
1618 if ( $this->
getRequest()->hasSafeMethod() ) {
1619 $trxProfiler->setExpectations( $limits[
'GET'], __METHOD__ );
1621 $trxProfiler->setExpectations( $limits[
'POST-nonwrite'], __METHOD__ );
1624 $trxProfiler->setExpectations( $limits[
'POST'], __METHOD__ );
1640 'timeSpentBackend' => (int)round(
$time * 1000 ),
1641 'hadError' =>
$e !==
null,
1648 $logCtx[
'errorCodes'][] = $msg->getApiCode();
1653 $msg =
"API {$request->getMethod()} " .
1655 " {$logCtx['ip']} " .
1656 "T={$logCtx['timeSpentBackend']}ms";
1665 if ( isset( $sensitive[$name] ) ) {
1667 $encValue =
'[redacted]';
1668 } elseif ( strlen(
$value ) > 256 ) {
1676 $msg .=
" {$name}={$encValue}";
1681 wfDebugLog(
'ApiAction',
'',
'private', $logCtx );
1692 $chars =
';@$!*(),/:';
1693 $numChars = strlen( $chars );
1694 for ( $i = 0; $i < $numChars; $i++ ) {
1695 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1699 return strtr( rawurlencode(
$s ), $table );
1707 return array_keys( $this->mParamsUsed );
1715 $this->mParamsUsed += array_fill_keys( (
array)
$params,
true );
1724 return array_keys( $this->mParamsSensitive );
1733 $this->mParamsSensitive += array_fill_keys( (
array)
$params,
true );
1743 $this->mParamsUsed[
$name] =
true;
1775 $this->mParamsUsed[
$name] =
true;
1786 $allParams = $this->
getRequest()->getValueNames();
1788 if ( !$this->mInternalMode ) {
1790 $printerParams = $this->mPrinter->encodeParamName(
1791 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1793 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1795 $unusedParams = array_diff( $allParams, $paramsUsed );
1798 if ( count( $unusedParams ) ) {
1800 'apierror-unrecognizedparams',
1802 count( $unusedParams )
1813 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
false ) {
1820 $printer->setHttpStatus( $httpCode );
1822 $printer->execute();
1823 $printer->closePrinter();
1849 ApiBase::PARAM_TYPE =>
'integer' 1852 ApiBase::PARAM_TYPE =>
'integer',
1856 ApiBase::PARAM_TYPE =>
'integer',
1860 ApiBase::PARAM_TYPE => [
'user',
'bot' ]
1863 ApiBase::PARAM_TYPE =>
'user',
1865 'requestid' =>
null,
1866 'servedby' =>
false,
1867 'curtimestamp' =>
false,
1868 'responselanginfo' =>
false,
1874 ApiBase::PARAM_TYPE => [
'plaintext',
'wikitext',
'html',
'raw',
'none',
'bc' ],
1880 'errorsuselocal' => [
1890 =>
'apihelp-help-example-main',
1891 'action=help&recursivesubmodules=1' 1892 =>
'apihelp-help-example-recursive',
1901 foreach ( $oldHelp
as $k => $v ) {
1902 if ( $k ===
'submodules' ) {
1903 $help[
'permissions'] =
'';
1907 $help[
'datatypes'] =
'';
1908 $help[
'templatedparams'] =
'';
1909 $help[
'credits'] =
'';
1913 [
'class' =>
'apihelp-block apihelp-permissions' ] );
1914 $m = $this->
msg(
'api-help-permissions' );
1915 if ( !$m->isDisabled() ) {
1916 $help[
'permissions'] .=
Html::rawElement(
'div', [
'class' =>
'apihelp-block-head' ],
1917 $m->numParams( count( self::$mRights ) )->parse()
1921 foreach ( self::$mRights
as $right => $rightMsg ) {
1924 $rightMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )->parse();
1927 $groups = array_map(
function ( $group ) {
1928 return $group ==
'*' ?
'all' : $group;
1932 $this->
msg(
'api-help-permissions-granted-to' )
1933 ->numParams( count( $groups ) )
1942 if ( empty( $options[
'nolead'] ) ) {
1943 $level = $options[
'headerlevel'];
1944 $tocnumber = &$options[
'tocnumber'];
1946 $header = $this->
msg(
'api-help-datatypes-header' )->parse();
1951 ' class="apihelp-header">',
1958 if ( $id !==
'main/datatypes' && $idFallback !==
'main/datatypes' ) {
1959 $headline =
'<div id="main/datatypes"></div>' . $headline;
1961 $help[
'datatypes'] .= $headline;
1962 $help[
'datatypes'] .= $this->
msg(
'api-help-datatypes' )->parseAsBlock();
1963 if ( !isset( $tocData[
'main/datatypes'] ) ) {
1964 $tocnumber[$level]++;
1965 $tocData[
'main/datatypes'] = [
1966 'toclevel' => count( $tocnumber ),
1968 'anchor' =>
'main/datatypes',
1970 'number' => implode(
'.', $tocnumber ),
1975 $header = $this->
msg(
'api-help-templatedparams-header' )->parse();
1980 ' class="apihelp-header">',
1987 if ( $id !==
'main/templatedparams' && $idFallback !==
'main/templatedparams' ) {
1988 $headline =
'<div id="main/templatedparams"></div>' . $headline;
1990 $help[
'templatedparams'] .= $headline;
1991 $help[
'templatedparams'] .= $this->
msg(
'api-help-templatedparams' )->parseAsBlock();
1992 if ( !isset( $tocData[
'main/templatedparams'] ) ) {
1993 $tocnumber[$level]++;
1994 $tocData[
'main/templatedparams'] = [
1995 'toclevel' => count( $tocnumber ),
1997 'anchor' =>
'main/templatedparams',
1999 'number' => implode(
'.', $tocnumber ),
2004 $header = $this->
msg(
'api-credits-header' )->parse();
2008 ' class="apihelp-header">',
2015 if ( $id !==
'main/credits' && $idFallback !==
'main/credits' ) {
2016 $headline =
'<div id="main/credits"></div>' . $headline;
2018 $help[
'credits'] .= $headline;
2019 $help[
'credits'] .= $this->
msg(
'api-credits' )->useDatabase(
false )->parseAsBlock();
2020 if ( !isset( $tocData[
'main/credits'] ) ) {
2021 $tocnumber[$level]++;
2022 $tocData[
'main/credits'] = [
2023 'toclevel' => count( $tocnumber ),
2025 'anchor' =>
'main/credits',
2027 'number' => implode(
'.', $tocnumber ),
2041 if ( !isset( $this->mCanApiHighLimits ) ) {
2042 $this->mCanApiHighLimits = $this->
getUser()->isAllowed(
'apihighlimits' );
2066 $this->
getRequest()->getHeader(
'Api-user-agent' ) .
' ' .
2067 $this->
getRequest()->getHeader(
'User-agent' )
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
setContext(IContextSource $context)
getAllowedParams()
See ApiBase for description.
getModuleManager()
Overrides to return this instance's module manager.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
getUserAgent()
Fetches the user agent used for this request.
const LIMIT_BIG2
Fast query, apihighlimits limit.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
setCacheMaxAge( $maxage)
Set how long the response should be cached.
getContinuationManager()
Get the continuation manager.
static $Modules
List of available modules: action name => module class.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
addRequestedFields( $force=[])
Add requested fields to the result.
static getRequestId()
Get the unique request ID.
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated...
modifyHelp(array &$help, array $options, array &$tocData)
processing should stop and the error should be shown to the user * false
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
This class holds a list of modules and handles instantiation.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
static instance()
Singleton.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfHostname()
Fetch server name for use in error reporting etc.
Exception used to abort API execution with an error.
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
An IContextSource implementation which will inherit context from another source but allow individual ...
static static static ApiFormatBase $mPrinter
checkReadOnly( $module)
Check if the DB is read-only for this user.
This manages continuation state.
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
canApiHighLimits()
Check whether the current user is allowed to use high limits.
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
this hook is for auditing only $response
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
see documentation in includes Linker php for Linker::makeImageLink & $time
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
static static static $mRights
List of user roles that are specifically relevant to the API.
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
setupModule()
Set up the module for response.
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
usually copyright or history_copyright This message must be in HTML not wikitext & $link
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
checkMaxLag( $module, $params)
Check the max lag if necessary.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
createPrinterByName( $format)
Create an instance of an output formatter by its name.
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
printResult( $httpCode=0)
Print results using the current printer.
static getMain()
Get the RequestContext object associated with the main request.
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
setCacheMode( $mode)
Set the type of caching headers which will be sent.
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
checkAsserts( $params)
Check asserts of the user's rights.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
handleException( $e)
Handle an exception as an API response.
const LIMIT_SML2
Slow query, apihighlimits limit.
getContext()
Get the base IContextSource object.
This is the main API class, used for both external and internal processing.
executeAction()
Execute the actual module, without any error handling.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
static closeElement( $element)
Returns "</$element>".
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
setupExecuteAction()
Set up for the execution.
getSensitiveParams()
Get the request parameters that should be considered sensitive.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
lacksSameOriginSecurity()
Get the security flag for the current request.
static runWithoutAbort( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
static factory( $code)
Get a cached or new language object for a given language code.
This class represents the result of the API operations.
markParamsSensitive( $params)
Mark parameters as sensitive.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
static static $Formats
List of available formats: format name => format class.
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request. ...
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
logRequest( $time, $e=null)
Log the preceding request.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
sendCacheHeaders( $isError)
Send caching headers.
checkBotReadOnly()
Check whether we are readonly for bots.
getModule()
Get the API module object.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
dieReadOnly()
Helper function for readonly errors.
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
static handleApiBeforeMainException( $e)
Handle an exception from the ApiBeforeMain hook.
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know...
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
This abstract class implements many basic API functions, and is the base of all API classes...
static singleton( $domain=false)
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Allows to change the fields on the form that will be generated $name
getPrinter()
Get the result formatter object.
getStatusValue()
Fetch the error status.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
markParamsUsed( $params)
Mark parameters as used.
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Interface for MediaWiki-localized exceptions.
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
execute()
Execute api request.
return true to allow those checks to and false if checking is done & $user
static listParam(array $list, $type='text')
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions. ...
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
getResult()
Get the ApiResult object associated with current request.
createErrorPrinter()
Create the printer for error output.
isWriteMode()
Indicates whether this module requires write mode.
ApiContinuationManager null $mContinuationManager
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.