26use Wikimedia\Timestamp\TimestampException;
56 'login' => ApiLogin::class,
57 'clientlogin' => ApiClientLogin::class,
58 'logout' => ApiLogout::class,
59 'createaccount' => ApiAMCreateAccount::class,
60 'linkaccount' => ApiLinkAccount::class,
61 'unlinkaccount' => ApiRemoveAuthenticationData::class,
62 'changeauthenticationdata' => ApiChangeAuthenticationData::class,
63 'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
64 'resetpassword' => ApiResetPassword::class,
65 'query' => ApiQuery::class,
66 'expandtemplates' => ApiExpandTemplates::class,
67 'parse' => ApiParse::class,
68 'stashedit' => ApiStashEdit::class,
69 'opensearch' => ApiOpenSearch::class,
70 'feedcontributions' => ApiFeedContributions::class,
71 'feedrecentchanges' => ApiFeedRecentChanges::class,
72 'feedwatchlist' => ApiFeedWatchlist::class,
73 'help' => ApiHelp::class,
74 'paraminfo' => ApiParamInfo::class,
75 'rsd' => ApiRsd::class,
76 'compare' => ApiComparePages::class,
77 'tokens' => ApiTokens::class,
78 'checktoken' => ApiCheckToken::class,
79 'cspreport' => ApiCSPReport::class,
80 'validatepassword' => ApiValidatePassword::class,
83 'purge' => ApiPurge::class,
84 'setnotificationtimestamp' => ApiSetNotificationTimestamp::class,
85 'rollback' => ApiRollback::class,
86 'delete' => ApiDelete::class,
87 'undelete' => ApiUndelete::class,
88 'protect' => ApiProtect::class,
89 'block' => ApiBlock::class,
90 'unblock' => ApiUnblock::class,
91 'move' => ApiMove::class,
92 'edit' => ApiEditPage::class,
93 'upload' => ApiUpload::class,
94 'filerevert' => ApiFileRevert::class,
95 'emailuser' => ApiEmailUser::class,
96 'watch' => ApiWatch::class,
97 'patrol' => ApiPatrol::class,
98 'import' => ApiImport::class,
99 'clearhasmsg' => ApiClearHasMsg::class,
100 'userrights' => ApiUserrights::class,
101 'options' => ApiOptions::class,
102 'imagerotate' => ApiImageRotate::class,
103 'revisiondelete' => ApiRevisionDelete::class,
104 'managetags' => ApiManageTags::class,
105 'tag' => ApiTag::class,
106 'mergehistory' => ApiMergeHistory::class,
107 'setpagelanguage' => ApiSetPageLanguage::class,
114 'json' => ApiFormatJson::class,
115 'jsonfm' => ApiFormatJson::class,
116 'php' => ApiFormatPhp::class,
117 'phpfm' => ApiFormatPhp::class,
118 'xml' => ApiFormatXml::class,
119 'xmlfm' => ApiFormatXml::class,
120 'rawfm' => ApiFormatJson::class,
121 'none' => ApiFormatNone::class,
132 'msg' =>
'right-writeapi',
136 'msg' =>
'api-help-right-apihighlimits',
172 $context = RequestContext::getMain();
176 $context = RequestContext::getMain();
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,
220 'userAgent' => $this->getUserAgent(),
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();
249 $code = RequestContext::sanitizeLangCode( $uselang );
251 if ( !$this->mInternalMode ) {
254 RequestContext::getMain()->setLanguage(
$wgLang );
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();
269 $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
270 $errorLang = Language::factory( $errorLangCode );
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;
324 if (
$request->getVal(
'callback' ) !==
null ) {
330 if (
$request->getVal(
'origin' ) ===
'*' ) {
337 if (
$request->getHeader(
'Treat-as-Untrusted' ) !==
false ) {
368 if ( $manager !==
null && $this->mContinuationManager !==
null ) {
369 throw new UnexpectedValueException(
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
537 }
catch ( Exception
$e ) {
541 }
catch ( Throwable
$e ) {
548 MediaWiki::preOutputCommit( $this->
getContext() );
556 while ( ob_get_level() > $obLevel ) {
571 MWExceptionHandler::rollbackMasterChangesAndLog(
$e );
575 Hooks::run(
'ApiMain::onException', [ $this,
$e ] );
587 $headerStr =
'MediaWiki-API-Error: ' . implode(
', ', $errCodes );
599 }
catch ( ApiUsageException $ex ) {
603 $this->
addWarning(
'apiwarn-errorprinterfailed' );
606 $this->mPrinter->addWarning( $error );
607 }
catch ( Exception $ex2 ) {
610 }
catch ( Throwable $ex2 ) {
617 $this->mPrinter =
null;
619 $this->mPrinter->forceDefaultParams();
620 if (
$e->getCode() ) {
641 $main =
new self( RequestContext::getMain(),
false );
642 $main->handleException(
$e );
643 $main->logRequest( 0,
$e );
644 }
catch ( Exception $e2 ) {
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";
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( [
834 foreach ( $requestedHeaders as $rHeader ) {
835 $rHeader = strtolower( trim( $rHeader ) );
836 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
837 wfDebugLog(
'api',
'CORS preflight failed on requested header: ' . $rHeader );
853 $wildcard = preg_quote( $wildcard,
'/' );
854 $wildcard = str_replace(
860 return "/^https?:\/\/$wildcard$/";
872 $out->addVaryHeader(
'Treat-as-Untrusted' );
876 if ( $config->get(
'VaryOnXFP' ) ) {
877 $out->addVaryHeader(
'X-Forwarded-Proto' );
880 if ( !$isError && $this->mModule &&
883 $etag = $this->mModule->getConditionalRequestData(
'etag' );
884 if ( $etag !==
null ) {
887 $lastMod = $this->mModule->getConditionalRequestData(
'last-modified' );
888 if ( $lastMod !==
null ) {
900 if ( isset( $this->mCacheControl[
'max-age'] ) ) {
901 $maxage = $this->mCacheControl[
'max-age'];
902 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
903 $this->mCacheMode !==
'private'
907 $privateCache =
'private, must-revalidate, max-age=' . $maxage;
909 if ( $this->mCacheMode ==
'private' ) {
910 $response->header(
"Cache-Control: $privateCache" );
914 $useKeyHeader = $config->get(
'UseKeyHeader' );
915 if ( $this->mCacheMode ==
'anon-public-user-private' ) {
916 $out->addVaryHeader(
'Cookie' );
918 if ( $useKeyHeader ) {
920 if (
$out->haveCacheVaryCookies() ) {
922 $response->header(
"Cache-Control: $privateCache" );
926 } elseif (
MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
929 $response->header(
"Cache-Control: $privateCache" );
937 if ( $useKeyHeader ) {
942 if ( !isset( $this->mCacheControl[
's-maxage'] ) ) {
943 $this->mCacheControl[
's-maxage'] = $this->
getParameter(
'smaxage' );
945 if ( !isset( $this->mCacheControl[
'max-age'] ) ) {
946 $this->mCacheControl[
'max-age'] = $this->
getParameter(
'maxage' );
949 if ( !$this->mCacheControl[
's-maxage'] && !$this->mCacheControl[
'max-age'] ) {
953 $response->header(
"Cache-Control: $privateCache" );
958 $this->mCacheControl[
'public'] =
true;
961 $maxAge = min( $this->mCacheControl[
's-maxage'], $this->mCacheControl[
'max-age'] );
962 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
968 foreach ( $this->mCacheControl as $name =>
$value ) {
969 if ( is_bool(
$value ) ) {
971 $ccHeader .= $separator .
$name;
975 $ccHeader .= $separator .
"$name=$value";
980 $response->header(
"Cache-Control: $ccHeader" );
987 if ( !isset( $this->mPrinter ) ) {
989 if ( !$this->mModuleMgr->isDefined(
$value,
'format' ) ) {
997 if ( !$this->mPrinter->canPrintErrors() ) {
1020 foreach (
$e->getStatusValue()->getErrorsByType(
$type ) as $error ) {
1023 } elseif (
$type !==
'error' ) {
1028 $class = preg_replace(
'#^Wikimedia\\\Rdbms\\\#',
'', get_class(
$e ) );
1029 $code =
'internal_api_error_' . $class;
1030 if ( $config->get(
'ShowExceptionDetails' ) ) {
1032 $msg =
$e->getMessageObject();
1034 $msg = Message::newFromSpecifier(
$e );
1038 $params = [
'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1040 $params = [
'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class(
$e ) ];
1060 $errors = $result->getResultData( [
'errors' ] );
1061 $warnings = $result->getResultData( [
'warnings' ] );
1063 if ( $warnings !==
null ) {
1066 if ( $errors !==
null ) {
1070 foreach ( $errors as $error ) {
1071 if ( isset( $error[
'code'] ) ) {
1072 $errorCodes[$error[
'code']] =
true;
1080 $errorCodes[$msg->getApiCode()] =
true;
1081 $formatter->addError( $modulePath, $msg );
1084 $formatter->addWarning( $modulePath, $msg );
1090 $path = [
'error' ];
1096 $result->addContentValue(
1100 $this->
msg(
'api-usage-docref',
$link )->inLanguage( $formatter->getLanguage() )->text()
1102 . $this->msg(
'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1106 if ( $config->get(
'ShowExceptionDetails' ) ) {
1107 $result->addContentValue(
1110 $this->
msg(
'api-exception-trace',
1114 MWExceptionHandler::getRedactedTraceAsString(
$e )
1115 )->inLanguage( $formatter->getLanguage() )->text()
1123 return array_keys( $errorCodes );
1135 if ( $requestid !==
null ) {
1139 if ( $this->
getConfig()->
get(
'ShowHostnames' ) && (
1140 in_array(
'servedby', $force,
true ) || $this->
getParameter(
'servedby' )
1146 $result->addValue(
null,
'curtimestamp',
wfTimestamp( TS_ISO_8601, time() ),
1151 $result->addValue(
null,
'uselang', $this->
getLanguage()->getCode(),
1166 $this->mAction =
$params[
'action'];
1179 $module = $this->mModuleMgr->getModule( $this->mAction,
'action' );
1180 if ( $module ===
null ) {
1184 [
'apierror-unknownaction',
wfEscapeWikiText( $this->mAction ) ],
'unknown_action'
1188 $moduleParams = $module->extractRequestParams();
1191 if ( $module->needsToken() ===
true ) {
1193 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1194 'See documentation for ApiBase::needsToken for details.'
1197 if ( $module->needsToken() ) {
1198 if ( !$module->mustBePosted() ) {
1200 "Module '{$module->getModuleName()}' must require POST to use tokens."
1204 if ( !isset( $moduleParams[
'token'] ) ) {
1207 $module->dieWithError( [
'apierror-missingparam',
'token' ] );
1211 $module->requirePostedParameters( [
'token' ] );
1213 if ( !$module->validateToken( $moduleParams[
'token'], $moduleParams ) ) {
1214 $module->dieWithError(
'apierror-badtoken' );
1225 $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1227 'host' => $dbLag[0],
1232 $jobQueueLagFactor = $this->
getConfig()->get(
'JobQueueIncludeInMaxLagFactor' );
1233 if ( $jobQueueLagFactor ) {
1235 $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1236 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1237 if ( $jobQueueLag > $lagInfo[
'lag'] ) {
1240 'lag' => $jobQueueLag,
1241 'type' =>
'jobqueue',
1242 'jobs' => $totalJobs,
1247 Hooks::runWithoutAbort(
'ApiMaxLagInfo', [ &$lagInfo ] );
1259 if ( $module->shouldCheckMaxlag() && isset(
$params[
'maxlag'] ) ) {
1262 if ( $lagInfo[
'lag'] > $maxLag ) {
1265 $response->header(
'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1266 $response->header(
'X-Database-Lag: ' . intval( $lagInfo[
'lag'] ) );
1268 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1270 [
'apierror-maxlag', $lagInfo[
'lag'], $lagInfo[
'host'] ],
1276 $this->
dieWithError( [
'apierror-maxlag-generic', $lagInfo[
'lag'] ],
'maxlag', $lagInfo );
1305 if ( $this->mInternalMode ) {
1310 if ( $this->
getRequest()->getMethod() !==
'GET' && $this->
getRequest()->getMethod() !==
'HEAD' ) {
1317 $ifNoneMatch = array_diff(
1318 $this->
getRequest()->getHeader(
'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1321 if ( $ifNoneMatch ) {
1322 if ( $ifNoneMatch === [
'*' ] ) {
1326 $etag = $module->getConditionalRequestData(
'etag' );
1329 if ( $ifNoneMatch && $etag !==
null ) {
1330 $test = substr( $etag, 0, 2 ) ===
'W/' ? substr( $etag, 2 ) : $etag;
1331 $match = array_map(
function (
$s ) {
1332 return substr(
$s, 0, 2 ) ===
'W/' ? substr(
$s, 2 ) :
$s;
1334 $return304 = in_array( $test, $match,
true );
1341 $i = strpos(
$value,
';' );
1342 if ( $i !==
false ) {
1351 $ts->getTimestamp( TS_RFC2822 ) ===
$value ||
1353 $ts->format(
'l, d-M-y H:i:s' ) .
' GMT' ===
$value ||
1355 $ts->format(
'D M j H:i:s Y' ) ===
$value ||
1356 $ts->format(
'D M j H:i:s Y' ) ===
$value
1358 $lastMod = $module->getConditionalRequestData(
'last-modified' );
1359 if ( $lastMod !==
null ) {
1363 'user' => $this->
getUser()->getTouched(),
1364 'epoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1366 if ( $this->
getConfig()->
get(
'UseSquid' ) ) {
1369 TS_MW, time() - $this->
getConfig()->
get(
'SquidMaxage' )
1372 Hooks::run(
'OutputPageCheckLastModified', [ &$modifiedTimes, $this->
getOutput() ] );
1373 $lastMod = max( $modifiedTimes );
1374 $return304 =
wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1377 }
catch ( TimestampException
$e ) {
1384 $this->
getRequest()->response()->statusHeader( 304 );
1387 Wikimedia\suppressWarnings();
1388 ini_set(
'zlib.output_compression', 0 );
1389 Wikimedia\restoreWarnings();
1405 !$user->isAllowed(
'read' )
1410 if ( $module->isWriteMode() ) {
1411 if ( !$this->mEnableWrite ) {
1413 } elseif ( !$user->isAllowed(
'writeapi' ) ) {
1415 } elseif ( $this->
getRequest()->getHeader(
'Promise-Non-Write-API-Action' ) ) {
1416 $this->
dieWithError(
'apierror-promised-nonwrite-api' );
1423 $message =
'hookaborted';
1424 if ( !Hooks::run(
'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1438 if ( $module->isWriteMode()
1439 && $this->getUser()->isBot()
1440 && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1452 $lagLimit = $this->
getConfig()->get(
'APIMaxLagThreshold' );
1453 $laggedServers = [];
1454 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1455 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1456 if ( $lag > $lagLimit ) {
1458 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) .
" ({$lag}s)";
1463 $replicaCount = $loadBalancer->getServerCount() - 1;
1464 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1465 $laggedServers = implode(
', ', $laggedServers );
1468 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1474 [
'readonlyreason' =>
"Waiting for $numLagged lagged database(s)" ]
1484 if ( isset(
$params[
'assert'] ) ) {
1486 switch (
$params[
'assert'] ) {
1488 if ( $user->isAnon() ) {
1493 if ( !$user->isAllowed(
'bot' ) ) {
1499 if ( isset(
$params[
'assertuser'] ) ) {
1501 if ( !$assertUser || !$this->
getUser()->equals( $assertUser ) ) {
1516 if ( !
$request->wasPosted() && $module->mustBePosted() ) {
1523 $this->mPrinter = $module->getCustomPrinter();
1524 if ( is_null( $this->mPrinter ) ) {
1529 if (
$request->getProtocol() ===
'http' && (
1530 $request->getSession()->shouldForceHTTPS() ||
1531 ( $this->getUser()->isLoggedIn() &&
1532 $this->getUser()->requiresHTTPS() )
1534 $this->
addDeprecation(
'apiwarn-deprecation-httpsexpected',
'https-expected' );
1549 $this->mModule = $module;
1551 if ( !$this->mInternalMode ) {
1565 if ( !$this->mInternalMode ) {
1571 Hooks::run(
'APIAfterExecute', [ &$module ] );
1575 if ( !$this->mInternalMode ) {
1589 $limits = $this->
getConfig()->get(
'TrxProfilerLimits' );
1590 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1591 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
1592 if ( $this->
getRequest()->hasSafeMethod() ) {
1593 $trxProfiler->setExpectations( $limits[
'GET'], __METHOD__ );
1595 $trxProfiler->setExpectations( $limits[
'POST-nonwrite'], __METHOD__ );
1598 $trxProfiler->setExpectations( $limits[
'POST'], __METHOD__ );
1614 'timeSpentBackend' => (int)round(
$time * 1000 ),
1615 'hadError' =>
$e !==
null,
1622 $logCtx[
'errorCodes'][] = $msg->getApiCode();
1627 $msg =
"API {$request->getMethod()} " .
1629 " {$logCtx['ip']} " .
1630 "T={$logCtx['timeSpentBackend']}ms";
1639 if ( isset( $sensitive[$name] ) ) {
1641 $encValue =
'[redacted]';
1642 } elseif ( strlen(
$value ) > 256 ) {
1650 $msg .=
" {$name}={$encValue}";
1655 wfDebugLog(
'ApiAction',
'',
'private', $logCtx );
1666 $chars =
';@$!*(),/:';
1667 $numChars = strlen( $chars );
1668 for ( $i = 0; $i < $numChars; $i++ ) {
1669 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1673 return strtr( rawurlencode(
$s ), $table );
1681 return array_keys( $this->mParamsUsed );
1689 $this->mParamsUsed += array_fill_keys( (
array)
$params,
true );
1698 return array_keys( $this->mParamsSensitive );
1707 $this->mParamsSensitive += array_fill_keys( (
array)
$params,
true );
1716 public function getVal( $name, $default =
null ) {
1717 $this->mParamsUsed[
$name] =
true;
1720 if (
$ret ===
null ) {
1721 if ( $this->
getRequest()->getArray( $name ) !==
null ) {
1724 $this->
addWarning( [
'apiwarn-unsupportedarray', $name ] );
1738 return $this->
getVal( $name,
null ) !==
null;
1749 $this->mParamsUsed[
$name] =
true;
1751 return $this->
getRequest()->getUpload( $name );
1760 $allParams = $this->
getRequest()->getValueNames();
1762 if ( !$this->mInternalMode ) {
1764 $printerParams = $this->mPrinter->encodeParamName(
1765 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1767 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1769 $unusedParams = array_diff( $allParams, $paramsUsed );
1772 if ( count( $unusedParams ) ) {
1774 'apierror-unrecognizedparams',
1775 Message::listParam( array_map(
'wfEscapeWikiText', $unusedParams ),
'comma' ),
1776 count( $unusedParams )
1787 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
false ) {
1794 $printer->setHttpStatus( $httpCode );
1796 $printer->execute();
1797 $printer->closePrinter();
1839 'requestid' =>
null,
1840 'servedby' =>
false,
1841 'curtimestamp' =>
false,
1842 'responselanginfo' =>
false,
1854 'errorsuselocal' => [
1864 =>
'apihelp-help-example-main',
1865 'action=help&recursivesubmodules=1'
1866 =>
'apihelp-help-example-recursive',
1875 foreach ( $oldHelp as $k => $v ) {
1876 if ( $k ===
'submodules' ) {
1877 $help[
'permissions'] =
'';
1881 $help[
'datatypes'] =
'';
1882 $help[
'templatedparams'] =
'';
1883 $help[
'credits'] =
'';
1886 $help[
'permissions'] .= Html::openElement(
'div',
1887 [
'class' =>
'apihelp-block apihelp-permissions' ] );
1888 $m = $this->
msg(
'api-help-permissions' );
1889 if ( !$m->isDisabled() ) {
1890 $help[
'permissions'] .= Html::rawElement(
'div', [
'class' =>
'apihelp-block-head' ],
1891 $m->numParams( count( self::$mRights ) )->parse()
1894 $help[
'permissions'] .= Html::openElement(
'dl' );
1895 foreach ( self::$mRights as $right => $rightMsg ) {
1896 $help[
'permissions'] .= Html::element(
'dt',
null, $right );
1898 $rightMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )->parse();
1899 $help[
'permissions'] .= Html::rawElement(
'dd',
null, $rightMsg );
1901 $groups = array_map(
function ( $group ) {
1902 return $group ==
'*' ?
'all' : $group;
1905 $help[
'permissions'] .= Html::rawElement(
'dd',
null,
1906 $this->
msg(
'api-help-permissions-granted-to' )
1907 ->numParams( count( $groups ) )
1908 ->params( Message::listParam( $groups ) )
1912 $help[
'permissions'] .= Html::closeElement(
'dl' );
1913 $help[
'permissions'] .= Html::closeElement(
'div' );
1916 if ( empty(
$options[
'nolead'] ) ) {
1918 $tocnumber = &
$options[
'tocnumber'];
1920 $header = $this->
msg(
'api-help-datatypes-header' )->parse();
1922 $id = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_PRIMARY );
1923 $idFallback = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_FALLBACK );
1925 ' class="apihelp-header">',
1932 if ( $id !==
'main/datatypes' && $idFallback !==
'main/datatypes' ) {
1933 $headline =
'<div id="main/datatypes"></div>' . $headline;
1935 $help[
'datatypes'] .= $headline;
1936 $help[
'datatypes'] .= $this->
msg(
'api-help-datatypes' )->parseAsBlock();
1937 if ( !isset( $tocData[
'main/datatypes'] ) ) {
1938 $tocnumber[$level]++;
1939 $tocData[
'main/datatypes'] = [
1940 'toclevel' => count( $tocnumber ),
1942 'anchor' =>
'main/datatypes',
1944 'number' => implode(
'.', $tocnumber ),
1949 $header = $this->
msg(
'api-help-templatedparams-header' )->parse();
1951 $id = Sanitizer::escapeIdForAttribute(
'main/templatedparams', Sanitizer::ID_PRIMARY );
1952 $idFallback = Sanitizer::escapeIdForAttribute(
'main/templatedparams', Sanitizer::ID_FALLBACK );
1954 ' class="apihelp-header">',
1961 if ( $id !==
'main/templatedparams' && $idFallback !==
'main/templatedparams' ) {
1962 $headline =
'<div id="main/templatedparams"></div>' . $headline;
1964 $help[
'templatedparams'] .= $headline;
1965 $help[
'templatedparams'] .= $this->
msg(
'api-help-templatedparams' )->parseAsBlock();
1966 if ( !isset( $tocData[
'main/templatedparams'] ) ) {
1967 $tocnumber[$level]++;
1968 $tocData[
'main/templatedparams'] = [
1969 'toclevel' => count( $tocnumber ),
1971 'anchor' =>
'main/templatedparams',
1973 'number' => implode(
'.', $tocnumber ),
1978 $header = $this->
msg(
'api-credits-header' )->parse();
1979 $id = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_PRIMARY );
1980 $idFallback = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_FALLBACK );
1982 ' class="apihelp-header">',
1989 if ( $id !==
'main/credits' && $idFallback !==
'main/credits' ) {
1990 $headline =
'<div id="main/credits"></div>' . $headline;
1992 $help[
'credits'] .= $headline;
1993 $help[
'credits'] .= $this->
msg(
'api-credits' )->useDatabase(
false )->parseAsBlock();
1994 if ( !isset( $tocData[
'main/credits'] ) ) {
1995 $tocnumber[$level]++;
1996 $tocData[
'main/credits'] = [
1997 'toclevel' => count( $tocnumber ),
1999 'anchor' =>
'main/credits',
2001 'number' => implode(
'.', $tocnumber ),
2015 if ( !isset( $this->mCanApiHighLimits ) ) {
2016 $this->mCanApiHighLimits = $this->
getUser()->isAllowed(
'apihighlimits' );
2040 $this->
getRequest()->getHeader(
'Api-user-agent' ) .
' ' .
2041 $this->
getRequest()->getHeader(
'User-agent' )
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfReadOnly()
Check whether the wiki is in read-only mode.
wfHostname()
Fetch server name for use in error reporting etc.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
This abstract class implements many basic API functions, and is the base of all API classes.
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
isWriteMode()
Indicates whether this module requires write mode.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
dieReadOnly()
Helper function for readonly errors.
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
const LIMIT_SML2
Slow query, apihighlimits limit.
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
const LIMIT_BIG2
Fast query, apihighlimits limit.
This manages continuation state.
This is the main API class, used for both external and internal processing.
static handleApiBeforeMainException( $e)
Handle an exception from the ApiBeforeMain hook.
getExamplesMessages()
@inheritDoc
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
getAllowedParams()
See ApiBase for description.
getSensitiveParams()
Get the request parameters that should be considered sensitive.
getPrinter()
Get the result formatter object.
logRequest( $time, $e=null)
Log the preceding request.
static $Modules
List of available modules: action name => module class.
sendCacheHeaders( $isError)
Send caching headers.
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
markParamsUsed( $params)
Mark parameters as used.
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
createPrinterByName( $format)
Create an instance of an output formatter by its name.
setCacheMaxAge( $maxage)
Set how long the response should be cached.
static $mRights
List of user roles that are specifically relevant to the API.
getResult()
Get the ApiResult object associated with current request.
createErrorPrinter()
Create the printer for error output.
executeAction()
Execute the actual module, without any error handling.
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
checkMaxLag( $module, $params)
Check the max lag if necessary.
checkAsserts( $params)
Check asserts of the user's rights.
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
setCacheMode( $mode)
Set the type of caching headers which will be sent.
setupModule()
Set up the module for response.
markParamsSensitive( $params)
Mark parameters as sensitive.
setupExecuteAction()
Set up for the execution.
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
checkBotReadOnly()
Check whether we are readonly for bots.
handleException( $e)
Handle an exception as an API response.
getUserAgent()
Fetches the user agent used for this request.
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
getModule()
Get the API module object.
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
addRequestedFields( $force=[])
Add requested fields to the result.
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
checkReadOnly( $module)
Check if the DB is read-only for this user.
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
getContinuationManager()
Get the continuation manager.
printResult( $httpCode=0)
Print results using the current printer.
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
lacksSameOriginSecurity()
Get the security flag for the current request.
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
getModuleManager()
Overrides to return this instance's module manager.
ApiContinuationManager null $mContinuationManager
substituteResultWithError( $e)
Replace the result data with the information about an exception.
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
canApiHighLimits()
Check whether the current user is allowed to use high limits.
static $Formats
List of available formats: format name => format class.
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
execute()
Execute api request.
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
This class holds a list of modules and handles instantiation.
This class represents the result of the API operations.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Exception used to abort API execution with an error.
getStatusValue()
Fetch the error status.
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getContext()
Get the base IContextSource object.
setContext(IContextSource $context)
An IContextSource implementation which will inherit context from another source but allow individual ...
WebRequest clone which takes values from a provided array.
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Library for creating and parsing MW-style timestamps.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
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
see documentation in includes Linker php for Linker::makeImageLink & $time
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that 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
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that 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
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Allows to change the fields on the form that will be generated $name
this hook is for auditing only $response
processing should stop and the error should be shown to the user * false
returning false will NOT prevent logging $e
Interface for MediaWiki-localized exceptions.
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))