26use Wikimedia\Timestamp\TimestampException;
58 'login' => ApiLogin::class,
59 'clientlogin' => ApiClientLogin::class,
60 'logout' => ApiLogout::class,
61 'createaccount' => ApiAMCreateAccount::class,
62 'linkaccount' => ApiLinkAccount::class,
63 'unlinkaccount' => ApiRemoveAuthenticationData::class,
64 'changeauthenticationdata' => ApiChangeAuthenticationData::class,
65 'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
66 'resetpassword' => ApiResetPassword::class,
67 'query' => ApiQuery::class,
68 'expandtemplates' => ApiExpandTemplates::class,
69 'parse' => ApiParse::class,
70 'stashedit' => ApiStashEdit::class,
71 'opensearch' => ApiOpenSearch::class,
72 'feedcontributions' => ApiFeedContributions::class,
73 'feedrecentchanges' => ApiFeedRecentChanges::class,
74 'feedwatchlist' => ApiFeedWatchlist::class,
75 'help' => ApiHelp::class,
76 'paraminfo' => ApiParamInfo::class,
77 'rsd' => ApiRsd::class,
78 'compare' => ApiComparePages::class,
79 'tokens' => ApiTokens::class,
80 'checktoken' => ApiCheckToken::class,
81 'cspreport' => ApiCSPReport::class,
82 'validatepassword' => ApiValidatePassword::class,
85 'purge' => ApiPurge::class,
86 'setnotificationtimestamp' => ApiSetNotificationTimestamp::class,
87 'rollback' => ApiRollback::class,
88 'delete' => ApiDelete::class,
89 'undelete' => ApiUndelete::class,
90 'protect' => ApiProtect::class,
91 'block' => ApiBlock::class,
92 'unblock' => ApiUnblock::class,
93 'move' => ApiMove::class,
94 'edit' => ApiEditPage::class,
95 'upload' => ApiUpload::class,
96 'filerevert' => ApiFileRevert::class,
97 'emailuser' => ApiEmailUser::class,
98 'watch' => ApiWatch::class,
99 'patrol' => ApiPatrol::class,
100 'import' => ApiImport::class,
101 'clearhasmsg' => ApiClearHasMsg::class,
102 'userrights' => ApiUserrights::class,
103 'options' => ApiOptions::class,
104 'imagerotate' => ApiImageRotate::class,
105 'revisiondelete' => ApiRevisionDelete::class,
106 'managetags' => ApiManageTags::class,
107 'tag' => ApiTag::class,
108 'mergehistory' => ApiMergeHistory::class,
109 'setpagelanguage' => ApiSetPageLanguage::class,
116 'json' => ApiFormatJson::class,
117 'jsonfm' => ApiFormatJson::class,
118 'php' => ApiFormatPhp::class,
119 'phpfm' => ApiFormatPhp::class,
120 'xml' => ApiFormatXml::class,
121 'xmlfm' => ApiFormatXml::class,
122 'rawfm' => ApiFormatJson::class,
123 'none' => ApiFormatNone::class,
134 'msg' =>
'right-writeapi',
138 'msg' =>
'api-help-right-apihighlimits',
192 parent::__construct( $this, $this->mInternalMode ?
'main_int' :
'main' );
196 if ( !$this->mInternalMode ) {
199 $originHeader =
$request->getHeader(
'Origin' );
200 if ( $originHeader ===
false ) {
203 $originHeader = trim( $originHeader );
204 $origins = preg_split(
'/\s+/', $originHeader );
206 $sessionCookies = array_intersect(
207 array_keys( $_COOKIE ),
208 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
210 if ( $origins && $sessionCookies && (
211 count( $origins ) !== 1 || !self::matchOrigin(
213 $config->get(
'CrossSiteAJAXdomains' ),
214 $config->get(
'CrossSiteAJAXdomainExceptions' )
217 LoggerFactory::getInstance(
'cors' )->warning(
218 'Non-whitelisted CORS request with session cookies', [
219 'origin' => $originHeader,
220 'cookies' => $sessionCookies,
222 'userAgent' => $this->getUserAgent(),
232 wfDebug(
"API: stripping user credentials when the same-origin policy is not applied\n" );
235 $request->response()->header(
'MediaWiki-Login-Suppressed: true' );
243 $uselang =
$request->getVal(
'uselang', self::API_DEFAULT_USELANG );
244 if ( $uselang ===
'user' ) {
248 if ( $uselang ===
'content' ) {
254 if ( !$this->mInternalMode ) {
263 $errorFormat =
$request->getVal(
'errorformat',
'bc' );
264 $errorLangCode =
$request->getVal(
'errorlang',
'uselang' );
265 $errorsUseDB =
$request->getCheck(
'errorsuselocal' );
266 if ( in_array( $errorFormat, [
'plaintext',
'wikitext',
'html',
'raw',
'none' ],
true ) ) {
267 if ( $errorLangCode ===
'uselang' ) {
269 } elseif ( $errorLangCode ===
'content' ) {
274 $errorLang = Language::factory( $errorLangCode );
277 $this->mResult, $errorLang, $errorFormat, $errorsUseDB
285 $this->mModuleMgr->addModules( self::$Modules,
'action' );
286 $this->mModuleMgr->addModules( $config->get(
'APIModules' ),
'action' );
287 $this->mModuleMgr->addModules( self::$Formats,
'format' );
288 $this->mModuleMgr->addModules( $config->get(
'APIFormatModules' ),
'format' );
290 Hooks::run(
'ApiMain::moduleManager', [ $this->mModuleMgr ] );
292 $this->mContinuationManager =
null;
293 $this->mEnableWrite = $enableWrite;
295 $this->mSquidMaxage = -1;
296 $this->mCommit =
false;
328 if (
$request->getVal(
'callback' ) !==
null ) {
334 if (
$request->getVal(
'origin' ) ===
'*' ) {
341 if (
$request->getHeader(
'Treat-as-Untrusted' ) !==
false ) {
372 if ( $manager !==
null && $this->mContinuationManager !==
null ) {
373 throw new UnexpectedValueException(
374 __METHOD__ .
': tried to set manager from ' . $manager->getSource() .
375 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
378 $this->mContinuationManager = $manager;
406 'max-age' => $maxage,
407 's-maxage' => $maxage
437 if ( !in_array( $mode, [
'private',
'public',
'anon-public-user-private' ] ) ) {
438 wfDebug( __METHOD__ .
": unrecognised cache mode \"$mode\"\n" );
446 if ( $mode !==
'private' ) {
447 wfDebug( __METHOD__ .
": ignoring request for $mode cache mode, private wiki\n" );
453 if ( $mode ===
'public' && $this->
getParameter(
'uselang' ) ===
'user' ) {
458 wfDebug( __METHOD__ .
": downgrading cache mode 'public' to " .
459 "'anon-public-user-private' due to uselang=user\n" );
460 $mode =
'anon-public-user-private';
463 wfDebug( __METHOD__ .
": setting cache mode $mode\n" );
464 $this->mCacheMode = $mode;
489 $printer = $this->mModuleMgr->getModule( $format,
'format' );
490 if ( $printer ===
null ) {
503 if ( $this->mInternalMode ) {
523 if ( $this->
getRequest()->getMethod() ===
'OPTIONS' ) {
529 $obLevel = ob_get_level();
532 $t = microtime(
true );
536 $runTime = microtime(
true ) -
$t;
538 if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
539 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
540 'api.' . $this->mModule->getModuleName() .
'.executeTiming', 1000 * $runTime
543 }
catch ( Exception
$e ) {
550 MediaWiki::preOutputCommit( $this->
getContext() );
558 while ( ob_get_level() > $obLevel ) {
573 MWExceptionHandler::rollbackMasterChangesAndLog(
$e );
577 Hooks::run(
'ApiMain::onException', [ $this,
$e ] );
589 $headerStr =
'MediaWiki-API-Error: ' . implode(
', ', $errCodes );
605 $this->
addWarning(
'apiwarn-errorprinterfailed' );
608 $this->mPrinter->addWarning( $error );
609 }
catch ( Exception $ex2 ) {
619 [
'apiwarn-errorprinterfailed-ex', $ex->getMessage() ],
'errorprinterfailed'
623 $this->mPrinter =
null;
625 $this->mPrinter->forceDefaultParams();
626 if (
$e->getCode() ) {
648 $main->handleException(
$e );
649 $main->logRequest( 0,
$e );
650 }
catch ( Exception $e2 ) {
656 $main->sendCacheHeaders(
true );
677 if ( $originParam ===
null ) {
685 $matchedOrigin =
false;
686 $allowTiming =
false;
689 if ( $originParam ===
'*' ) {
695 $matchedOrigin =
true;
697 $allowCredentials =
'false';
703 $originHeader =
$request->getHeader(
'Origin' );
704 if ( $originHeader ===
false ) {
707 $originHeader = trim( $originHeader );
708 $origins = preg_split(
'/\s+/', $originHeader );
711 if ( !in_array( $originParam, $origins ) ) {
715 $response->header(
'Cache-Control: no-cache' );
716 echo
"'origin' parameter does not match Origin header\n";
724 $config->get(
'CrossSiteAJAXdomains' ),
725 $config->get(
'CrossSiteAJAXdomainExceptions' )
728 $allowOrigin = $originHeader;
729 $allowCredentials =
'true';
730 $allowTiming = $originHeader;
733 if ( $matchedOrigin ) {
734 $requestedMethod =
$request->getHeader(
'Access-Control-Request-Method' );
735 $preflight =
$request->getMethod() ===
'OPTIONS' && $requestedMethod !==
false;
738 if ( $requestedMethod !==
'POST' && $requestedMethod !==
'GET' ) {
740 $response->header(
'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
744 $requestedHeaders =
$request->getHeader(
'Access-Control-Request-Headers' );
745 if ( $requestedHeaders !==
false ) {
746 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
747 $response->header(
'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
750 $response->header(
'Access-Control-Allow-Headers: ' . $requestedHeaders );
754 $response->header(
'Access-Control-Allow-Methods: POST, GET' );
755 } elseif (
$request->getMethod() !==
'POST' &&
$request->getMethod() !==
'GET' ) {
758 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
763 $response->header(
"Access-Control-Allow-Origin: $allowOrigin" );
764 $response->header(
"Access-Control-Allow-Credentials: $allowCredentials" );
766 if ( $allowTiming !==
false ) {
767 $response->header(
"Timing-Allow-Origin: $allowTiming" );
772 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
773 .
'MediaWiki-Login-Suppressed'
777 $response->header(
'MediaWiki-CORS-Rejection: Origin mismatch' );
781 $this->
getOutput()->addVaryHeader(
'Origin' );
796 foreach ( $rules as $rule ) {
797 if ( preg_match( self::wildcardToRegex( $rule ),
$value ) ) {
799 foreach ( $exceptions as $exc ) {
800 if ( preg_match( self::wildcardToRegex( $exc ),
$value ) ) {
820 if ( trim( $requestedHeaders ) ===
'' ) {
823 $requestedHeaders = explode(
',', $requestedHeaders );
824 $allowedAuthorHeaders = array_flip( [
837 foreach ( $requestedHeaders as $rHeader ) {
838 $rHeader = strtolower( trim( $rHeader ) );
839 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
840 wfDebugLog(
'api',
'CORS preflight failed on requested header: ' . $rHeader );
856 $wildcard = preg_quote( $wildcard,
'/' );
857 $wildcard = str_replace(
863 return "/^https?:\/\/$wildcard$/";
875 $out->addVaryHeader(
'Treat-as-Untrusted' );
879 if ( $config->get(
'VaryOnXFP' ) ) {
880 $out->addVaryHeader(
'X-Forwarded-Proto' );
883 if ( !$isError && $this->mModule &&
886 $etag = $this->mModule->getConditionalRequestData(
'etag' );
887 if ( $etag !==
null ) {
890 $lastMod = $this->mModule->getConditionalRequestData(
'last-modified' );
891 if ( $lastMod !==
null ) {
903 if ( isset( $this->mCacheControl[
'max-age'] ) ) {
904 $maxage = $this->mCacheControl[
'max-age'];
905 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
906 $this->mCacheMode !==
'private'
910 $privateCache =
'private, must-revalidate, max-age=' . $maxage;
912 if ( $this->mCacheMode ==
'private' ) {
913 $response->header(
"Cache-Control: $privateCache" );
917 $useKeyHeader = $config->get(
'UseKeyHeader' );
918 if ( $this->mCacheMode ==
'anon-public-user-private' ) {
919 $out->addVaryHeader(
'Cookie' );
921 if ( $useKeyHeader ) {
923 if (
$out->haveCacheVaryCookies() ) {
925 $response->header(
"Cache-Control: $privateCache" );
929 } elseif (
MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
932 $response->header(
"Cache-Control: $privateCache" );
940 if ( $useKeyHeader ) {
945 if ( !isset( $this->mCacheControl[
's-maxage'] ) ) {
946 $this->mCacheControl[
's-maxage'] = $this->
getParameter(
'smaxage' );
948 if ( !isset( $this->mCacheControl[
'max-age'] ) ) {
949 $this->mCacheControl[
'max-age'] = $this->
getParameter(
'maxage' );
952 if ( !$this->mCacheControl[
's-maxage'] && !$this->mCacheControl[
'max-age'] ) {
956 $response->header(
"Cache-Control: $privateCache" );
961 $this->mCacheControl[
'public'] =
true;
964 $maxAge = min( $this->mCacheControl[
's-maxage'], $this->mCacheControl[
'max-age'] );
965 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
971 foreach ( $this->mCacheControl as $name =>
$value ) {
972 if ( is_bool(
$value ) ) {
974 $ccHeader .= $separator .
$name;
978 $ccHeader .= $separator .
"$name=$value";
983 $response->header(
"Cache-Control: $ccHeader" );
990 if ( !isset( $this->mPrinter ) ) {
992 if ( !$this->mModuleMgr->isDefined(
$value,
'format' ) ) {
1000 if ( !$this->mPrinter->canPrintErrors() ) {
1026 foreach (
$e->getStatusValue()->getErrorsByType(
$type ) as $error ) {
1029 } elseif (
$type !==
'error' ) {
1033 $data = Wikimedia\quietCall( [
$e,
'getMessageArray' ] );
1034 $code = $data[
'code'];
1035 $info = $data[
'info'];
1036 unset( $data[
'code'], $data[
'info'] );
1041 $class = preg_replace(
'#^Wikimedia\\\Rdbms\\\#',
'', get_class(
$e ) );
1042 $code =
'internal_api_error_' . $class;
1043 if ( (
$e instanceof
DBQueryError ) && !$config->get(
'ShowSQLErrors' ) ) {
1044 $params = [
'apierror-databaseerror', WebRequest::getRequestId() ];
1047 $msg =
$e->getMessageObject();
1049 $msg = Message::newFromSpecifier(
$e );
1053 $params = [
'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1072 $errors = $result->getResultData( [
'errors' ] );
1073 $warnings = $result->getResultData( [
'warnings' ] );
1075 if ( $warnings !==
null ) {
1078 if ( $errors !==
null ) {
1082 foreach ( $errors as $error ) {
1083 if ( isset( $error[
'code'] ) ) {
1084 $errorCodes[$error[
'code']] =
true;
1092 $errorCodes[$msg->getApiCode()] =
true;
1093 $formatter->addError( $modulePath, $msg );
1096 $formatter->addWarning( $modulePath, $msg );
1102 $path = [
'error' ];
1108 $result->addContentValue(
1112 $this->
msg(
'api-usage-docref',
$link )->inLanguage( $formatter->getLanguage() )->text()
1114 . $this->msg(
'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1118 if ( $config->get(
'ShowExceptionDetails' ) &&
1119 ( !
$e instanceof
DBError || $config->get(
'ShowDBErrorBacktrace' ) )
1121 $result->addContentValue(
1124 $this->
msg(
'api-exception-trace',
1128 MWExceptionHandler::getRedactedTraceAsString(
$e )
1129 )->inLanguage( $formatter->getLanguage() )->text()
1137 return array_keys( $errorCodes );
1149 if ( $requestid !==
null ) {
1153 if ( $this->
getConfig()->
get(
'ShowHostnames' ) && (
1154 in_array(
'servedby', $force,
true ) || $this->
getParameter(
'servedby' )
1160 $result->addValue(
null,
'curtimestamp',
wfTimestamp( TS_ISO_8601, time() ),
1165 $result->addValue(
null,
'uselang', $this->
getLanguage()->getCode(),
1180 $this->mAction =
$params[
'action'];
1193 $module = $this->mModuleMgr->getModule( $this->mAction,
'action' );
1194 if ( $module ===
null ) {
1198 [
'apierror-unknownaction',
wfEscapeWikiText( $this->mAction ) ],
'unknown_action'
1202 $moduleParams = $module->extractRequestParams();
1205 if ( $module->needsToken() ===
true ) {
1207 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1208 'See documentation for ApiBase::needsToken for details.'
1211 if ( $module->needsToken() ) {
1212 if ( !$module->mustBePosted() ) {
1214 "Module '{$module->getModuleName()}' must require POST to use tokens."
1218 if ( !isset( $moduleParams[
'token'] ) ) {
1221 $module->dieWithError( [
'apierror-missingparam',
'token' ] );
1225 $module->requirePostedParameters( [
'token' ] );
1227 if ( !$module->validateToken( $moduleParams[
'token'], $moduleParams ) ) {
1228 $module->dieWithError(
'apierror-badtoken' );
1239 $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1241 'host' => $dbLag[0],
1246 $jobQueueLagFactor = $this->
getConfig()->get(
'JobQueueIncludeInMaxLagFactor' );
1247 if ( $jobQueueLagFactor ) {
1250 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1251 if ( $jobQueueLag > $lagInfo[
'lag'] ) {
1254 'lag' => $jobQueueLag,
1255 'type' =>
'jobqueue',
1256 'jobs' => $totalJobs,
1271 if ( $module->shouldCheckMaxlag() && isset(
$params[
'maxlag'] ) ) {
1274 if ( $lagInfo[
'lag'] > $maxLag ) {
1277 $response->header(
'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1278 $response->header(
'X-Database-Lag: ' . intval( $lagInfo[
'lag'] ) );
1280 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1282 [
'apierror-maxlag', $lagInfo[
'lag'], $lagInfo[
'host'] ],
1288 $this->
dieWithError( [
'apierror-maxlag-generic', $lagInfo[
'lag'] ],
'maxlag', $lagInfo );
1317 if ( $this->mInternalMode ) {
1322 if ( $this->
getRequest()->getMethod() !==
'GET' && $this->
getRequest()->getMethod() !==
'HEAD' ) {
1329 $ifNoneMatch = array_diff(
1330 $this->
getRequest()->getHeader(
'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1333 if ( $ifNoneMatch ) {
1334 if ( $ifNoneMatch === [
'*' ] ) {
1338 $etag = $module->getConditionalRequestData(
'etag' );
1341 if ( $ifNoneMatch && $etag !==
null ) {
1342 $test = substr( $etag, 0, 2 ) ===
'W/' ? substr( $etag, 2 ) : $etag;
1343 $match = array_map(
function (
$s ) {
1344 return substr(
$s, 0, 2 ) ===
'W/' ? substr(
$s, 2 ) :
$s;
1346 $return304 = in_array( $test, $match,
true );
1353 $i = strpos(
$value,
';' );
1354 if ( $i !==
false ) {
1363 $ts->getTimestamp( TS_RFC2822 ) ===
$value ||
1365 $ts->format(
'l, d-M-y H:i:s' ) .
' GMT' ===
$value ||
1367 $ts->format(
'D M j H:i:s Y' ) ===
$value ||
1368 $ts->format(
'D M j H:i:s Y' ) ===
$value
1370 $lastMod = $module->getConditionalRequestData(
'last-modified' );
1371 if ( $lastMod !==
null ) {
1375 'user' => $this->
getUser()->getTouched(),
1376 'epoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1378 if ( $this->
getConfig()->
get(
'UseSquid' ) ) {
1381 TS_MW, time() - $this->
getConfig()->
get(
'SquidMaxage' )
1384 Hooks::run(
'OutputPageCheckLastModified', [ &$modifiedTimes, $this->
getOutput() ] );
1385 $lastMod = max( $modifiedTimes );
1386 $return304 =
wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1389 }
catch ( TimestampException
$e ) {
1396 $this->
getRequest()->response()->statusHeader( 304 );
1399 Wikimedia\suppressWarnings();
1400 ini_set(
'zlib.output_compression', 0 );
1401 Wikimedia\restoreWarnings();
1417 !$user->isAllowed(
'read' )
1422 if ( $module->isWriteMode() ) {
1423 if ( !$this->mEnableWrite ) {
1425 } elseif ( !$user->isAllowed(
'writeapi' ) ) {
1427 } elseif ( $this->
getRequest()->getHeader(
'Promise-Non-Write-API-Action' ) ) {
1428 $this->
dieWithError(
'apierror-promised-nonwrite-api' );
1435 $message =
'hookaborted';
1436 if ( !Hooks::run(
'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1450 if ( $module->isWriteMode()
1451 && $this->getUser()->isBot()
1452 && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1464 $lagLimit = $this->
getConfig()->get(
'APIMaxLagThreshold' );
1465 $laggedServers = [];
1466 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1467 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1468 if ( $lag > $lagLimit ) {
1470 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) .
" ({$lag}s)";
1475 $replicaCount = $loadBalancer->getServerCount() - 1;
1476 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1477 $laggedServers = implode(
', ', $laggedServers );
1480 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1486 [
'readonlyreason' =>
"Waiting for $numLagged lagged database(s)" ]
1496 if ( isset(
$params[
'assert'] ) ) {
1498 switch (
$params[
'assert'] ) {
1500 if ( $user->isAnon() ) {
1505 if ( !$user->isAllowed(
'bot' ) ) {
1511 if ( isset(
$params[
'assertuser'] ) ) {
1513 if ( !$assertUser || !$this->
getUser()->equals( $assertUser ) ) {
1528 if ( !
$request->wasPosted() && $module->mustBePosted() ) {
1535 $this->mPrinter = $module->getCustomPrinter();
1536 if ( is_null( $this->mPrinter ) ) {
1541 if (
$request->getProtocol() ===
'http' &&
1543 $this->getConfig()->get(
'ForceHTTPS' ) ||
1544 $request->getSession()->shouldForceHTTPS() ||
1545 ( $this->getUser()->isLoggedIn() &&
1546 $this->getUser()->requiresHTTPS() )
1549 $this->
addDeprecation(
'apiwarn-deprecation-httpsexpected',
'https-expected' );
1559 $this->mModule = $module;
1561 if ( !$this->mInternalMode ) {
1575 if ( !$this->mInternalMode ) {
1583 Hooks::run(
'APIAfterExecute', [ &$module ] );
1587 if ( !$this->mInternalMode ) {
1601 $limits = $this->
getConfig()->get(
'TrxProfilerLimits' );
1602 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1603 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
1604 if ( $this->
getRequest()->hasSafeMethod() ) {
1605 $trxProfiler->setExpectations( $limits[
'GET'], __METHOD__ );
1607 $trxProfiler->setExpectations( $limits[
'POST-nonwrite'], __METHOD__ );
1610 $trxProfiler->setExpectations( $limits[
'POST'], __METHOD__ );
1626 'timeSpentBackend' => (int)round(
$time * 1000 ),
1627 'hadError' =>
$e !==
null,
1634 $logCtx[
'errorCodes'][] = $msg->getApiCode();
1639 $msg =
"API {$request->getMethod()} " .
1641 " {$logCtx['ip']} " .
1642 "T={$logCtx['timeSpentBackend']}ms";
1651 if ( isset( $sensitive[$name] ) ) {
1653 $encValue =
'[redacted]';
1654 } elseif ( strlen(
$value ) > 256 ) {
1662 $msg .=
" {$name}={$encValue}";
1667 wfDebugLog(
'ApiAction',
'',
'private', $logCtx );
1678 $chars =
';@$!*(),/:';
1679 $numChars = strlen( $chars );
1680 for ( $i = 0; $i < $numChars; $i++ ) {
1681 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1685 return strtr( rawurlencode(
$s ), $table );
1693 return array_keys( $this->mParamsUsed );
1701 $this->mParamsUsed += array_fill_keys( (array)
$params,
true );
1710 return array_keys( $this->mParamsSensitive );
1719 $this->mParamsSensitive += array_fill_keys( (array)
$params,
true );
1728 public function getVal( $name, $default =
null ) {
1729 $this->mParamsUsed[
$name] =
true;
1732 if (
$ret ===
null ) {
1733 if ( $this->
getRequest()->getArray( $name ) !==
null ) {
1736 $this->
addWarning( [
'apiwarn-unsupportedarray', $name ] );
1750 return $this->
getVal( $name,
null ) !==
null;
1761 $this->mParamsUsed[
$name] =
true;
1763 return $this->
getRequest()->getUpload( $name );
1772 $allParams = $this->
getRequest()->getValueNames();
1774 if ( !$this->mInternalMode ) {
1776 $printerParams = $this->mPrinter->encodeParamName(
1777 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1779 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1781 $unusedParams = array_diff( $allParams, $paramsUsed );
1784 if ( count( $unusedParams ) ) {
1786 'apierror-unrecognizedparams',
1787 Message::listParam( array_map(
'wfEscapeWikiText', $unusedParams ),
'comma' ),
1788 count( $unusedParams )
1799 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
false ) {
1806 $printer->setHttpStatus( $httpCode );
1808 $printer->execute();
1809 $printer->closePrinter();
1851 'requestid' =>
null,
1852 'servedby' =>
false,
1853 'curtimestamp' =>
false,
1854 'responselanginfo' =>
false,
1866 'errorsuselocal' => [
1876 =>
'apihelp-help-example-main',
1877 'action=help&recursivesubmodules=1'
1878 =>
'apihelp-help-example-recursive',
1887 foreach ( $oldHelp as $k => $v ) {
1888 if ( $k ===
'submodules' ) {
1889 $help[
'permissions'] =
'';
1893 $help[
'datatypes'] =
'';
1894 $help[
'credits'] =
'';
1897 $help[
'permissions'] .= Html::openElement(
'div',
1898 [
'class' =>
'apihelp-block apihelp-permissions' ] );
1899 $m = $this->
msg(
'api-help-permissions' );
1900 if ( !$m->isDisabled() ) {
1901 $help[
'permissions'] .= Html::rawElement(
'div', [
'class' =>
'apihelp-block-head' ],
1902 $m->numParams( count( self::$mRights ) )->parse()
1905 $help[
'permissions'] .= Html::openElement(
'dl' );
1906 foreach ( self::$mRights as $right => $rightMsg ) {
1907 $help[
'permissions'] .= Html::element(
'dt',
null, $right );
1909 $rightMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )->parse();
1910 $help[
'permissions'] .= Html::rawElement(
'dd',
null, $rightMsg );
1912 $groups = array_map(
function ( $group ) {
1913 return $group ==
'*' ?
'all' : $group;
1916 $help[
'permissions'] .= Html::rawElement(
'dd',
null,
1917 $this->
msg(
'api-help-permissions-granted-to' )
1918 ->numParams( count( $groups ) )
1919 ->params( Message::listParam( $groups ) )
1923 $help[
'permissions'] .= Html::closeElement(
'dl' );
1924 $help[
'permissions'] .= Html::closeElement(
'div' );
1927 if ( empty(
$options[
'nolead'] ) ) {
1929 $tocnumber = &
$options[
'tocnumber'];
1931 $header = $this->
msg(
'api-help-datatypes-header' )->parse();
1933 $id = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_PRIMARY );
1934 $idFallback = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_FALLBACK );
1936 ' class="apihelp-header">',
1943 if ( $id !==
'main/datatypes' && $idFallback !==
'main/datatypes' ) {
1944 $headline =
'<div id="main/datatypes"></div>' . $headline;
1946 $help[
'datatypes'] .= $headline;
1947 $help[
'datatypes'] .= $this->
msg(
'api-help-datatypes' )->parseAsBlock();
1948 if ( !isset( $tocData[
'main/datatypes'] ) ) {
1949 $tocnumber[$level]++;
1950 $tocData[
'main/datatypes'] = [
1951 'toclevel' => count( $tocnumber ),
1953 'anchor' =>
'main/datatypes',
1955 'number' => implode(
'.', $tocnumber ),
1960 $header = $this->
msg(
'api-credits-header' )->parse();
1961 $id = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_PRIMARY );
1962 $idFallback = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_FALLBACK );
1964 ' class="apihelp-header">',
1971 if ( $id !==
'main/credits' && $idFallback !==
'main/credits' ) {
1972 $headline =
'<div id="main/credits"></div>' . $headline;
1974 $help[
'credits'] .= $headline;
1975 $help[
'credits'] .= $this->
msg(
'api-credits' )->useDatabase(
false )->parseAsBlock();
1976 if ( !isset( $tocData[
'main/credits'] ) ) {
1977 $tocnumber[$level]++;
1978 $tocData[
'main/credits'] = [
1979 'toclevel' => count( $tocnumber ),
1981 'anchor' =>
'main/credits',
1983 'number' => implode(
'.', $tocnumber ),
1997 if ( !isset( $this->mCanApiHighLimits ) ) {
1998 $this->mCanApiHighLimits = $this->
getUser()->isAllowed(
'apihighlimits' );
2022 $this->
getRequest()->getHeader(
'Api-user-agent' ) .
' ' .
2023 $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.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
const LIMIT_SML2
Slow query, apihighlimits limit.
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.
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.
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
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.
handleException(Exception $e)
Handle an exception as an API response.
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.
Extension of RawMessage implementing IApiMessage.
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 singleton( $domain=false)
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Library for creating and parsing MW-style timestamps.
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
static getMain()
Get the RequestContext object associated with the main request.
This exception will be thrown when dieUsage is called to stop module execution.
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...
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
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.