51 'login' =>
'ApiLogin',
52 'clientlogin' =>
'ApiClientLogin',
53 'logout' =>
'ApiLogout',
54 'createaccount' =>
'ApiAMCreateAccount',
55 'linkaccount' =>
'ApiLinkAccount',
56 'unlinkaccount' =>
'ApiRemoveAuthenticationData',
57 'changeauthenticationdata' =>
'ApiChangeAuthenticationData',
58 'removeauthenticationdata' =>
'ApiRemoveAuthenticationData',
59 'resetpassword' =>
'ApiResetPassword',
60 'query' =>
'ApiQuery',
61 'expandtemplates' =>
'ApiExpandTemplates',
62 'parse' =>
'ApiParse',
63 'stashedit' =>
'ApiStashEdit',
64 'opensearch' =>
'ApiOpenSearch',
65 'feedcontributions' =>
'ApiFeedContributions',
66 'feedrecentchanges' =>
'ApiFeedRecentChanges',
67 'feedwatchlist' =>
'ApiFeedWatchlist',
69 'paraminfo' =>
'ApiParamInfo',
71 'compare' =>
'ApiComparePages',
72 'tokens' =>
'ApiTokens',
73 'checktoken' =>
'ApiCheckToken',
74 'cspreport' =>
'ApiCSPReport',
77 'purge' =>
'ApiPurge',
78 'setnotificationtimestamp' =>
'ApiSetNotificationTimestamp',
79 'rollback' =>
'ApiRollback',
80 'delete' =>
'ApiDelete',
81 'undelete' =>
'ApiUndelete',
82 'protect' =>
'ApiProtect',
83 'block' =>
'ApiBlock',
84 'unblock' =>
'ApiUnblock',
86 'edit' =>
'ApiEditPage',
87 'upload' =>
'ApiUpload',
88 'filerevert' =>
'ApiFileRevert',
89 'emailuser' =>
'ApiEmailUser',
90 'watch' =>
'ApiWatch',
91 'patrol' =>
'ApiPatrol',
92 'import' =>
'ApiImport',
93 'clearhasmsg' =>
'ApiClearHasMsg',
94 'userrights' =>
'ApiUserrights',
95 'options' =>
'ApiOptions',
96 'imagerotate' =>
'ApiImageRotate',
97 'revisiondelete' =>
'ApiRevisionDelete',
98 'managetags' =>
'ApiManageTags',
100 'mergehistory' =>
'ApiMergeHistory',
107 'json' =>
'ApiFormatJson',
108 'jsonfm' =>
'ApiFormatJson',
109 'php' =>
'ApiFormatPhp',
110 'phpfm' =>
'ApiFormatPhp',
111 'xml' =>
'ApiFormatXml',
112 'xmlfm' =>
'ApiFormatXml',
113 'rawfm' =>
'ApiFormatJson',
114 'none' =>
'ApiFormatNone',
126 'msg' =>
'right-writeapi',
130 'msg' =>
'api-help-right-apihighlimits',
184 parent::__construct( $this, $this->mInternalMode ?
'main_int' :
'main' );
188 if ( !$this->mInternalMode ) {
191 $originHeader =
$request->getHeader(
'Origin' );
192 if ( $originHeader ===
false ) {
195 $originHeader = trim( $originHeader );
196 $origins = preg_split(
'/\s+/', $originHeader );
198 $sessionCookies = array_intersect(
199 array_keys( $_COOKIE ),
200 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
202 if ( $origins && $sessionCookies && (
203 count( $origins ) !== 1 || !self::matchOrigin(
205 $config->get(
'CrossSiteAJAXdomains' ),
206 $config->get(
'CrossSiteAJAXdomainExceptions' )
210 'Non-whitelisted CORS request with session cookies', [
211 'origin' => $originHeader,
212 'cookies' => $sessionCookies,
224 wfDebug(
"API: stripping user credentials when the same-origin policy is not applied\n" );
225 $wgUser =
new User();
231 if ( $uselang ===
'user' ) {
235 if ( $uselang ===
'content' ) {
237 $uselang = $wgContLang->getCode();
241 if ( !$this->mInternalMode ) {
249 $this->mModuleMgr->addModules( self::$Modules,
'action' );
250 $this->mModuleMgr->addModules( $config->get(
'APIModules' ),
'action' );
251 $this->mModuleMgr->addModules( self::$Formats,
'format' );
252 $this->mModuleMgr->addModules( $config->get(
'APIFormatModules' ),
'format' );
254 Hooks::run(
'ApiMain::moduleManager', [ $this->mModuleMgr ] );
258 $this->mResult->setErrorFormatter( $this->mErrorFormatter );
259 $this->mResult->setMainForContinuation( $this );
260 $this->mContinuationManager = null;
261 $this->mEnableWrite = $enableWrite;
263 $this->mSquidMaxage = -1;
264 $this->mCommit =
false;
296 if (
$request->getVal(
'callback' ) !== null ) {
302 if (
$request->getVal(
'origin' ) ===
'*' ) {
309 if (
$request->getHeader(
'Treat-as-Untrusted' ) !==
false ) {
340 if ( $manager !== null ) {
342 throw new InvalidArgumentException( __METHOD__ .
': Was passed ' .
343 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
346 if ( $this->mContinuationManager !== null ) {
347 throw new UnexpectedValueException(
348 __METHOD__ .
': tried to set manager from ' . $manager->getSource() .
349 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
353 $this->mContinuationManager = $manager;
381 'max-age' => $maxage,
382 's-maxage' => $maxage
412 if ( !in_array( $mode, [
'private',
'public',
'anon-public-user-private' ] ) ) {
413 wfDebug( __METHOD__ .
": unrecognised cache mode \"$mode\"\n" );
421 if ( $mode !==
'private' ) {
422 wfDebug( __METHOD__ .
": ignoring request for $mode cache mode, private wiki\n" );
428 if ( $mode ===
'public' && $this->
getParameter(
'uselang' ) ===
'user' ) {
433 wfDebug( __METHOD__ .
": downgrading cache mode 'public' to " .
434 "'anon-public-user-private' due to uselang=user\n" );
435 $mode =
'anon-public-user-private';
438 wfDebug( __METHOD__ .
": setting cache mode $mode\n" );
439 $this->mCacheMode = $mode;
464 $printer = $this->mModuleMgr->getModule( $format,
'format' );
465 if ( $printer === null ) {
466 $this->
dieUsage(
"Unrecognized format: {$format}",
'unknown_format' );
476 if ( $this->mInternalMode ) {
496 if ( $this->
getRequest()->getMethod() ===
'OPTIONS' ) {
502 $obLevel = ob_get_level();
505 $t = microtime(
true );
509 $runTime = microtime(
true ) -
$t;
511 if ( $this->mModule->isWriteMode() && $this->
getRequest()->wasPosted() ) {
513 'api.' . $this->mModule->getModuleName() .
'.executeTiming', 1000 * $runTime
516 }
catch ( Exception
$e ) {
531 while ( ob_get_level() > $obLevel ) {
556 Hooks::run(
'ApiMain::onException', [ $this, $e ] );
559 if ( !( $e instanceof UsageException ) ) {
573 $headerStr =
'MediaWiki-API-Error: ' . $errCode;
574 if ( $e->getCode() === 0 ) {
577 $response->header( $headerStr,
true, $e->getCode() );
588 }
catch ( UsageException $ex ) {
592 'Error printer failed (will retry without params): ' . $ex->getMessage()
594 $this->mPrinter = null;
596 $this->mPrinter->forceDefaultParams();
616 $main->handleException( $e );
617 $main->logRequest( 0, $e );
618 }
catch ( Exception $e2 ) {
624 $main->sendCacheHeaders(
true );
645 if ( $originParam === null ) {
653 $matchOrigin =
false;
654 $allowTiming =
false;
657 if ( $originParam ===
'*' ) {
661 $allowCredentials =
'false';
667 $originHeader =
$request->getHeader(
'Origin' );
668 if ( $originHeader ===
false ) {
671 $originHeader = trim( $originHeader );
672 $origins = preg_split(
'/\s+/', $originHeader );
675 if ( !in_array( $originParam, $origins ) ) {
679 $response->header(
'Cache-Control: no-cache' );
680 echo
"'origin' parameter does not match Origin header\n";
686 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
688 $config->get(
'CrossSiteAJAXdomains' ),
689 $config->get(
'CrossSiteAJAXdomainExceptions' )
692 $allowOrigin = $originHeader;
693 $allowCredentials =
'true';
694 $allowTiming = $originHeader;
697 if ( $matchOrigin ) {
698 $requestedMethod =
$request->getHeader(
'Access-Control-Request-Method' );
699 $preflight =
$request->getMethod() ===
'OPTIONS' && $requestedMethod !==
false;
702 if ( $requestedMethod !==
'POST' && $requestedMethod !==
'GET' ) {
707 $requestedHeaders =
$request->getHeader(
'Access-Control-Request-Headers' );
708 if ( $requestedHeaders !==
false ) {
709 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
712 $response->header(
'Access-Control-Allow-Headers: ' . $requestedHeaders );
716 $response->header(
'Access-Control-Allow-Methods: POST, GET' );
719 $response->header(
"Access-Control-Allow-Origin: $allowOrigin" );
720 $response->header(
"Access-Control-Allow-Credentials: $allowCredentials" );
722 if ( $allowTiming !==
false ) {
723 $response->header(
"Timing-Allow-Origin: $allowTiming" );
728 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
734 $this->
getOutput()->addVaryHeader(
'Origin' );
749 foreach ( $rules
as $rule ) {
750 if ( preg_match( self::wildcardToRegex( $rule ),
$value ) ) {
752 foreach ( $exceptions
as $exc ) {
753 if ( preg_match( self::wildcardToRegex( $exc ),
$value ) ) {
773 if ( trim( $requestedHeaders ) ===
'' ) {
776 $requestedHeaders = explode(
',', $requestedHeaders );
777 $allowedAuthorHeaders = array_flip( [
790 foreach ( $requestedHeaders
as $rHeader ) {
791 $rHeader = strtolower( trim( $rHeader ) );
792 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
793 wfDebugLog(
'api',
'CORS preflight failed on requested header: ' . $rHeader );
809 $wildcard = preg_quote( $wildcard,
'/' );
810 $wildcard = str_replace(
816 return "/^https?:\/\/$wildcard$/";
828 $out->addVaryHeader(
'Treat-as-Untrusted' );
832 if ( $config->get(
'VaryOnXFP' ) ) {
833 $out->addVaryHeader(
'X-Forwarded-Proto' );
836 if ( !$isError && $this->mModule &&
839 $etag = $this->mModule->getConditionalRequestData(
'etag' );
840 if ( $etag !== null ) {
843 $lastMod = $this->mModule->getConditionalRequestData(
'last-modified' );
844 if ( $lastMod !== null ) {
856 if ( isset( $this->mCacheControl[
'max-age'] ) ) {
857 $maxage = $this->mCacheControl[
'max-age'];
858 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
859 $this->mCacheMode !==
'private'
863 $privateCache =
'private, must-revalidate, max-age=' . $maxage;
865 if ( $this->mCacheMode ==
'private' ) {
866 $response->header(
"Cache-Control: $privateCache" );
870 $useKeyHeader = $config->get(
'UseKeyHeader' );
871 if ( $this->mCacheMode ==
'anon-public-user-private' ) {
872 $out->addVaryHeader(
'Cookie' );
874 if ( $useKeyHeader ) {
876 if (
$out->haveCacheVaryCookies() ) {
878 $response->header(
"Cache-Control: $privateCache" );
882 } elseif (
MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
885 $response->header(
"Cache-Control: $privateCache" );
893 if ( $useKeyHeader ) {
898 if ( !isset( $this->mCacheControl[
's-maxage'] ) ) {
899 $this->mCacheControl[
's-maxage'] = $this->
getParameter(
'smaxage' );
901 if ( !isset( $this->mCacheControl[
'max-age'] ) ) {
902 $this->mCacheControl[
'max-age'] = $this->
getParameter(
'maxage' );
905 if ( !$this->mCacheControl[
's-maxage'] && !$this->mCacheControl[
'max-age'] ) {
909 $response->header(
"Cache-Control: $privateCache" );
914 $this->mCacheControl[
'public'] =
true;
917 $maxAge = min( $this->mCacheControl[
's-maxage'], $this->mCacheControl[
'max-age'] );
918 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
925 if ( is_bool(
$value ) ) {
927 $ccHeader .= $separator .
$name;
931 $ccHeader .= $separator .
"$name=$value";
936 $response->header(
"Cache-Control: $ccHeader" );
943 if ( !isset( $this->mPrinter ) ) {
945 if ( !$this->mModuleMgr->isDefined(
$value,
'format' ) ) {
946 $value = self::API_DEFAULT_FORMAT;
953 if ( !$this->mPrinter->canPrintErrors() ) {
971 $errMessage =
$e->getMessageArray();
975 if ( (
$e instanceof
DBQueryError ) && !$config->get(
'ShowSQLErrors' ) ) {
976 $info =
'Database query error';
978 $info =
"Exception Caught: {$e->getMessage()}";
982 'code' =>
'internal_api_error_' . get_class(
$e ),
1006 if ( $config->get(
'ShowExceptionDetails' ) ) {
1016 $warnings =
$result->getResultData( [
'warnings' ] );
1021 if ( !is_null( $requestid ) ) {
1024 if ( $config->get(
'ShowHostnames' ) ) {
1028 if ( $warnings !== null ) {
1034 return $errMessage[
'code'];
1045 if ( !is_null( $requestid ) ) {
1046 $result->addValue( null,
'requestid', $requestid );
1049 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1063 $this->mAction =
$params[
'action'];
1065 if ( !is_string( $this->mAction ) ) {
1066 $this->
dieUsage(
'The API requires a valid action parameter',
'unknown_action' );
1080 $module = $this->mModuleMgr->getModule( $this->mAction,
'action' );
1081 if ( $module === null ) {
1082 $this->
dieUsage(
'The API requires a valid action parameter',
'unknown_action' );
1084 $moduleParams = $module->extractRequestParams();
1087 if ( $module->needsToken() ===
true ) {
1089 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1090 'See documentation for ApiBase::needsToken for details.'
1093 if ( $module->needsToken() ) {
1094 if ( !$module->mustBePosted() ) {
1096 "Module '{$module->getModuleName()}' must require POST to use tokens."
1100 if ( !isset( $moduleParams[
'token'] ) ) {
1101 $this->
dieUsageMsg( [
'missingparam',
'token' ] );
1104 if ( !$this->
getConfig()->
get(
'DebugAPI' ) &&
1106 $module->encodeParamName(
'token' ),
1111 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1112 'found in the query string, but must be in the POST body',
1117 if ( !$module->validateToken( $moduleParams[
'token'], $moduleParams ) ) {
1132 if ( $module->shouldCheckMaxlag() && isset(
$params[
'maxlag'] ) ) {
1135 if ( $lag > $maxLag ) {
1138 $response->header(
'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1139 $response->header(
'X-Database-Lag: ' . intval( $lag ) );
1141 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1142 $this->
dieUsage(
"Waiting for $host: $lag seconds lagged",
'maxlag' );
1145 $this->
dieUsage(
"Waiting for a database server: $lag seconds lagged",
'maxlag' );
1174 if ( $this->mInternalMode ) {
1179 if ( $this->
getRequest()->getMethod() !==
'GET' && $this->
getRequest()->getMethod() !==
'HEAD' ) {
1186 $ifNoneMatch = array_diff(
1190 if ( $ifNoneMatch ) {
1191 if ( $ifNoneMatch === [
'*' ] ) {
1195 $etag = $module->getConditionalRequestData(
'etag' );
1198 if ( $ifNoneMatch && $etag !== null ) {
1199 $test = substr( $etag, 0, 2 ) ===
'W/' ? substr( $etag, 2 ) : $etag;
1200 $match = array_map(
function (
$s ) {
1201 return substr(
$s, 0, 2 ) ===
'W/' ? substr(
$s, 2 ) :
$s;
1203 $return304 = in_array( $test, $match,
true );
1210 $i = strpos(
$value,
';' );
1211 if ( $i !==
false ) {
1222 $ts->format(
'l, d-M-y H:i:s' ) .
' GMT' ===
$value ||
1224 $ts->format(
'D M j H:i:s Y' ) ===
$value ||
1225 $ts->format(
'D M j H:i:s Y' ) ===
$value
1227 $lastMod = $module->getConditionalRequestData(
'last-modified' );
1228 if ( $lastMod !== null ) {
1232 'user' => $this->
getUser()->getTouched(),
1233 'epoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1235 if ( $this->
getConfig()->
get(
'UseSquid' ) ) {
1242 $lastMod = max( $modifiedTimes );
1253 $this->
getRequest()->response()->statusHeader( 304 );
1256 MediaWiki\suppressWarnings();
1257 ini_set(
'zlib.output_compression', 0 );
1258 MediaWiki\restoreWarnings();
1274 !
$user->isAllowed(
'read' )
1279 if ( $module->isWriteMode() ) {
1280 if ( !$this->mEnableWrite ) {
1282 } elseif ( !
$user->isAllowed(
'writeapi' ) ) {
1284 } elseif ( $this->
getRequest()->getHeader(
'Promise-Non-Write-API-Action' ) ) {
1286 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1287 'promised-nonwrite-api'
1296 if ( !
Hooks::run(
'ApiCheckCanExecute', [ $module,
$user, &$message ] ) ) {
1310 if ( $module->isWriteMode()
1311 && in_array(
'bot', $this->
getUser()->getGroups() )
1312 &&
wfGetLB()->getServerCount() > 1
1324 $lagLimit = $this->
getConfig()->get(
'APIMaxLagThreshold' );
1325 $laggedServers = [];
1327 foreach ( $loadBalancer->getLagTimes()
as $serverIndex => $lag ) {
1328 if ( $lag > $lagLimit ) {
1330 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) .
" ({$lag}s)";
1335 $slaveCount =
wfGetLB()->getServerCount() - 1;
1336 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1337 $laggedServers = implode(
', ', $laggedServers );
1340 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1343 $parsed = $this->
parseMsg( [
'readonlytext' ] );
1349 [
'readonlyreason' =>
"Waiting for $numLagged lagged database(s)" ]
1359 if ( isset(
$params[
'assert'] ) ) {
1361 switch (
$params[
'assert'] ) {
1363 if (
$user->isAnon() ) {
1364 $this->
dieUsage(
'Assertion that the user is logged in failed',
'assertuserfailed' );
1368 if ( !
$user->isAllowed(
'bot' ) ) {
1369 $this->
dieUsage(
'Assertion that the user has the bot right failed',
'assertbotfailed' );
1383 if ( !
$request->wasPosted() && $module->mustBePosted() ) {
1390 $this->mPrinter = $module->getCustomPrinter();
1391 if ( is_null( $this->mPrinter ) ) {
1396 if (
$request->getProtocol() ===
'http' && (
1397 $request->getSession()->shouldForceHTTPS() ||
1398 ( $this->
getUser()->isLoggedIn() &&
1399 $this->
getUser()->requiresHTTPS() )
1402 $this->
setWarning(
'HTTP used when HTTPS was expected' );
1412 $this->mModule = $module;
1414 if ( !$this->mInternalMode ) {
1428 if ( !$this->mInternalMode ) {
1436 Hooks::run(
'APIAfterExecute', [ &$module ] );
1440 if ( !$this->mInternalMode ) {
1454 $limits = $this->
getConfig()->get(
'TrxProfilerLimits' );
1456 if ( $this->
getRequest()->hasSafeMethod() ) {
1457 $trxProfiler->setExpectations( $limits[
'GET'], __METHOD__ );
1459 $trxProfiler->setExpectations( $limits[
'POST-nonwrite'], __METHOD__ );
1462 $trxProfiler->setExpectations( $limits[
'POST'], __METHOD__ );
1478 'timeSpentBackend' => (int) round(
$time * 1000 ),
1479 'hadError' =>
$e !== null,
1489 $msg =
"API {$request->getMethod()} " .
1491 " {$logCtx['ip']} " .
1492 "T={$logCtx['timeSpentBackend']}ms";
1500 if ( strlen(
$value ) > 256 ) {
1508 $msg .=
" {$name}={$encValue}";
1513 wfDebugLog(
'ApiAction',
'',
'private', $logCtx );
1524 $chars =
';@$!*(),/:';
1525 $numChars = strlen( $chars );
1526 for ( $i = 0; $i < $numChars; $i++ ) {
1527 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1531 return strtr( rawurlencode(
$s ), $table );
1539 return array_keys( $this->mParamsUsed );
1547 $this->mParamsUsed += array_fill_keys( (
array)
$params,
true );
1557 $this->mParamsUsed[
$name] =
true;
1560 if (
$ret === null ) {
1565 "Parameter '$name' uses unsupported PHP array syntax"
1591 $this->mParamsUsed[
$name] =
true;
1602 $allParams = $this->
getRequest()->getValueNames();
1604 if ( !$this->mInternalMode ) {
1606 $printerParams = array_map(
1607 [ $this->mPrinter,
'encodeParamName' ],
1608 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1610 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1612 $unusedParams = array_diff( $allParams, $paramsUsed );
1615 if ( count( $unusedParams ) ) {
1616 $s = count( $unusedParams ) > 1 ?
's' :
'';
1617 $this->
setWarning(
"Unrecognized parameter$s: '" . implode( $unusedParams,
"', '" ) .
"'" );
1627 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
false ) {
1628 $this->
setWarning(
'SECURITY WARNING: $wgDebugAPI is enabled' );
1633 $printer->execute();
1634 $printer->closePrinter();
1660 ApiBase::PARAM_TYPE =>
'integer'
1663 ApiBase::PARAM_TYPE =>
'integer',
1667 ApiBase::PARAM_TYPE =>
'integer',
1671 ApiBase::PARAM_TYPE => [
'user',
'bot' ]
1673 'requestid' => null,
1674 'servedby' =>
false,
1675 'curtimestamp' =>
false,
1687 =>
'apihelp-help-example-main',
1688 'action=help&recursivesubmodules=1'
1689 =>
'apihelp-help-example-recursive',
1698 foreach ( $oldHelp
as $k => $v ) {
1699 if ( $k ===
'submodules' ) {
1700 $help[
'permissions'] =
'';
1704 $help[
'datatypes'] =
'';
1705 $help[
'credits'] =
'';
1709 [
'class' =>
'apihelp-block apihelp-permissions' ] );
1710 $m = $this->
msg(
'api-help-permissions' );
1711 if ( !$m->isDisabled() ) {
1712 $help[
'permissions'] .=
Html::rawElement(
'div', [
'class' =>
'apihelp-block-head' ],
1713 $m->numParams( count( self::$mRights ) )->parse()
1717 foreach ( self::$mRights
as $right => $rightMsg ) {
1718 $help[
'permissions'] .=
Html::element(
'dt', null, $right );
1720 $rightMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )->parse();
1723 $groups = array_map(
function ( $group ) {
1724 return $group ==
'*' ?
'all' : $group;
1728 $this->
msg(
'api-help-permissions-granted-to' )
1729 ->numParams( count( $groups ) )
1730 ->params( $this->
getLanguage()->commaList( $groups ) )
1738 if ( empty( $options[
'nolead'] ) ) {
1739 $level = $options[
'headerlevel'];
1740 $tocnumber = &$options[
'tocnumber'];
1742 $header = $this->
msg(
'api-help-datatypes-header' )->parse();
1745 if ( !$this->
getConfig()->
get(
'ExperimentalHtmlIds' ) ) {
1750 [
'id' =>
'main/datatypes',
'class' =>
'apihelp-header' ],
1753 $help[
'datatypes'] .= $this->
msg(
'api-help-datatypes' )->parseAsBlock();
1754 if ( !isset( $tocData[
'main/datatypes'] ) ) {
1755 $tocnumber[$level]++;
1756 $tocData[
'main/datatypes'] = [
1757 'toclevel' => count( $tocnumber ),
1759 'anchor' =>
'main/datatypes',
1761 'number' => implode(
'.', $tocnumber ),
1767 if ( !$this->
getConfig()->
get(
'ExperimentalHtmlIds' ) ) {
1771 $header = $this->
msg(
'api-credits-header' )->parse();
1773 [
'id' =>
'main/credits',
'class' =>
'apihelp-header' ],
1776 $help[
'credits'] .= $this->
msg(
'api-credits' )->useDatabase(
false )->parseAsBlock();
1777 if ( !isset( $tocData[
'main/credits'] ) ) {
1778 $tocnumber[$level]++;
1779 $tocData[
'main/credits'] = [
1780 'toclevel' => count( $tocnumber ),
1782 'anchor' =>
'main/credits',
1784 'number' => implode(
'.', $tocnumber ),
1798 if ( !isset( $this->mCanApiHighLimits ) ) {
1799 $this->mCanApiHighLimits = $this->
getUser()->isAllowed(
'apihighlimits' );
1823 $this->
getRequest()->getHeader(
'Api-user-agent' ) .
' ' .
1824 $this->
getRequest()->getHeader(
'User-agent' )
1841 $this->mPrinter->setHelp(
$help );
1854 $cacheHelpTimeout = $this->
getConfig()->get(
'APICacheHelpTimeout' );
1863 [ $this,
'reallyMakeHelpMsg' ]
1876 $msg = parent::makeHelpMsg();
1878 $asterisks = str_repeat(
'*** ', 14 );
1879 $msg .=
"\n\n$asterisks Modules $asterisks\n\n";
1881 foreach ( $this->mModuleMgr->getNames(
'action' )
as $name ) {
1882 $module = $this->mModuleMgr->getModule(
$name );
1883 $msg .= self::makeHelpMsgHeader( $module,
'action' );
1885 $msg2 = $module->makeHelpMsg();
1886 if ( $msg2 !==
false ) {
1892 $msg .=
"\n$asterisks Permissions $asterisks\n\n";
1893 foreach ( self::$mRights
as $right => $rightMsg ) {
1894 $rightsMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )
1895 ->useDatabase(
false )
1896 ->inLanguage(
'en' )
1899 $msg .=
'* ' . $right .
" *\n $rightsMsg" .
1900 "\nGranted to:\n " . str_replace(
'*',
'all', implode(
', ', $groups ) ) .
"\n\n";
1903 $msg .=
"\n$asterisks Formats $asterisks\n\n";
1904 foreach ( $this->mModuleMgr->getNames(
'format' )
as $name ) {
1905 $module = $this->mModuleMgr->getModule(
$name );
1906 $msg .= self::makeHelpMsgHeader( $module,
'format' );
1907 $msg2 = $module->makeHelpMsg();
1908 if ( $msg2 !==
false ) {
1914 $credits = $this->
msg(
'api-credits' )->useDatabase(
'false' )->inLanguage(
'en' )->text();
1915 $credits = str_replace(
"\n",
"\n ", $credits );
1916 $msg .=
"\n*** Credits: ***\n $credits\n";
1930 $modulePrefix = $module->getModulePrefix();
1931 if ( strval( $modulePrefix ) !==
'' ) {
1932 $modulePrefix =
"($modulePrefix) ";
1935 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1963 parent::__construct( $message,
$code );
1964 $this->mCodestr = $codestr;
1965 $this->mExtraData = $extradata;
1969 if ( !is_string( $codestr ) || $codestr ===
'' ) {
1970 throw new InvalidArgumentException(
'Invalid $codestr, was ' .
1971 ( $codestr ===
'' ?
'empty string' : gettype( $codestr ) )
1989 'info' => $this->getMessage()
1991 if ( is_array( $this->mExtraData ) ) {
2002 return "{$this->getCodeString()}: {$this->getMessage()}";
dieUsageMsgOrDebug($error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
setContext(IContextSource $context)
Set the IContextSource object.
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
getAllowedParams()
See ApiBase for description.
static closeElement($element)
Returns "</$element>".
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...
getStats()
Get the Stats object.
getUserAgent()
Fetches the user agent used for this request.
const LIMIT_BIG2
Fast query, apihighlimits limit.
static getMainWANInstance()
Get the main WAN cache object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
getContinuationManager()
Get the continuation manager.
static $Modules
List of available modules: action name => module class.
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
Database error base class.
printResult($isError)
Print results using the current printer.
checkConditionalRequestHeaders($module)
Check selected RFC 7232 precondition headers.
the array() calling protocol came about after MediaWiki 1.4rc1.
getLanguage()
Get the Language object.
static getRequestId()
Get the unique request ID.
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated...
getParameter($paramName, $parseLimit=true)
Get a value for the given parameter.
modifyHelp(array &$help, array $options, array &$tocData)
__construct($context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
processing should stop and the error should be shown to the user * false
This class holds a list of modules and handles instantiation.
checkReadOnly($module)
Check if the DB is read-only for this user.
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
static instance()
Singleton.
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
wfHostname()
Fetch server name for use in error reporting etc.
An IContextSource implementation which will inherit context from another source but allow individual ...
static matchRequestedHeaders($requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
static static static ApiFormatBase $mPrinter
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
setCacheMaxAge($maxage)
Set how long the response should be cached.
This manages continuation state.
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
canApiHighLimits()
Check whether the current user is allowed to use high limits.
wfUrlencode($s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
this hook is for auditing only $response
when a variable name is used in a it is silently declared as a new local masking the global
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
setCacheMode($mode)
Set the type of caching headers which will be sent.
see documentation in includes Linker php for Linker::makeImageLink & $time
static static static $mRights
List of user roles that are specifically relevant to the API.
setupExternalResponse($module, $params)
Check POST for external response and setup result printer.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
setCacheControl($directives)
Set directives (key/value pairs) for the Cache-Control header.
errorMessageFromException($e)
Create an error message for the given exception.
static isEveryoneAllowed($right)
Check if all users may be assumed to have the given permission.
static sanitizeLangCode($code)
Accepts a language code and ensures it's sane.
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
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 '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. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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!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.
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
makeHelpMsg()
Override the parent to generate help messages for all available modules.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getRequest()
Get the WebRequest object.
static wildcardToRegex($wildcard)
Helper function to convert wildcard string into a regex '*' => '.
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
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
msg()
Get a Message object with context set Parameters are the same as wfMessage()
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
wfGetLB($wiki=false)
Get a load balancer object.
wfReadOnly()
Check whether the wiki is in read-only mode.
static getMain()
Static methods.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
getConfig()
Get the Config object.
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.
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
setupExecuteAction()
Set up for the execution.
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
lacksSameOriginSecurity()
Get the security flag for the current request.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
createPrinterByName($format)
Create an instance of an output formatter by its name.
getModuleName()
Get the name of the module being executed by this instance.
static dieReadOnly()
Helper function for readonly errors.
static matchOrigin($value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions. ...
This class represents the result of the API operations.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static makeHelpMsgHeader($module, $paramName)
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
encodeRequestLogValue($s)
Encode a value in a format suitable for a space-separated log line.
checkMaxLag($module, $params)
Check the max lag if necessary.
setWarning($warning)
Set warning section for this module.
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
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 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
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
static static $Formats
List of available formats: format name => format class.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request. ...
logRequest($time, $e=null)
Log the preceding request.
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
static rollbackMasterChangesAndLog($e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
static escapeId($id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it. ...
getUpload($name)
Get a request upload, and register the fact that it was used, for logging.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
markParamsUsed($params)
Mark parameters as used.
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
checkBotReadOnly()
Check whether we are readonly for bots.
getModule()
Get the API module object.
error also a ContextSource you ll probably need to make sure the header is varied on $request
setHelp($help=true)
Sets whether the pretty-printer should format bold and $italics$.
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
WebRequest clone which takes values from a provided array.
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():
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
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 abstract class implements many basic API functions, and is the base of all API classes...
getPrinter()
Get the result formatter object.
wfMemcKey()
Make a cache key for the local wiki.
checkAsserts($params)
Check asserts of the user's rights.
parseMsg($error)
Return the error message related to a certain array.
static logException($e)
Log an exception to the exception log (if enabled).
getCheck($name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
static getVersion($flags= '', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
sendCacheHeaders($isError)
Send caching headers.
getVal($name, $default=null)
Get a request value, and register the fact that it was used, for logging.
__construct($message, $codestr, $code=0, $extradata=null)
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
getUser()
Get the User object.
substituteResultWithError($e)
Replace the result data with the information about an exception.
Library for creating and parsing MW-style timestamps.
dieUsageMsg($error)
Output the error message related to a certain array.
static getGroupsWithPermission($role)
Get all the groups who have a given permission.
execute()
Execute api request.
This exception will be thrown when dieUsage is called to stop module execution.
getResult()
Get the ApiResult object associated with current request.
checkExecutePermissions($module)
Check for sufficient permissions to execute.
createErrorPrinter()
Create the printer for error output.
isWriteMode()
Indicates whether this module requires write mode.
ApiContinuationManager null $mContinuationManager
setContinuationManager($manager)
Set the continuation manager.
getOutput()
Get the OutputPage object.
Allows to change the fields on the form that will be generated $name
handleException(Exception $e)
Handle an exception as an API response.